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 (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |