加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

PHP耽误静态绑定行使要领实例理会

发布时间:2020-09-21 07:08:47 所属栏目:编程 来源:网络整理
导读:这篇文章首要先容了PHP耽误静态绑定行使要领实例理会,文中通过示例代码先容的很是具体,对各人的进修可能事变具有必然的参考进修代价,必要的伴侣可以参考下

PHP的担任模子中有一个存在已久的题目,那就是在父类中引用扩展类的最终状态较量坚苦。我们来看一下代码清单5-11中的例子。

代码清单5-11 意想不到的担任

<?php class ParentBase { static $property = 'Parent Value'; public static function render() { return self::$property; } } class Descendant extends ParentBase { static $property = 'Descendant Value'; } echo Descendant::render(); Parent Value

在这个例子中,render()要领中行使了self要害字,这是指ParentBase类而不是指Descendant类。在ParentBase::render()要领中没法会见$property的最终值。为了办理这个题目,必要在子类中重写render()要领。

通过引入耽误静态绑定成果,可以行使static浸染域要害字会见类的属性可能要领的最终值,如代码所示。

<?php class ParentBase { static $property = 'Parent Value'; public static function render() { return static::$property; } } class Descendant extends ParentBase { static $property = 'Descendant Value'; } echo Descendant::render(); Descendant Value

通过行使静态浸染域,可以逼迫PHP在最终的类中查找全部属性的值。除了这个耽误绑定举动,PHP还添加了get_called_class()函数,这应承搜查担任的要领是从哪个派生类挪用的。以下代码表现了行使get_called_class()函数获适合前的类挪用场景的要领。

行使get_called_class()要领

<?php class ParentBase { public static function render() { return get_called_class(); } } class Decendant extends ParentBase {} echo Descendant::render(); Descendant

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读