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
以上内容即为本文的全部介绍,希望能对各位的学习有所助益,同时也欢迎大家多多支持本站。 可以用父类声明通用静态方法,子类覆盖被调用的方法,再比较两类写法的输出。判断重点是调用入口对应的类和定义方法的类是否相同;在继承层次较深时,这个差异会直接影响被执行的实现。