php - 如果存在,如何让 PHP 父函数引用子函数中的覆盖函数?
问题描述
给定以下代码:
class A {
public static function one() {
return "results from Parent::one";
}
public function two() {
return "Parent::two got info: ".self::one();
}
}
class B extends A {
public static function one() {
return "results from child::one";
}
}
$a=new B();
print "calling two I get: ". $a->two()."\n";
print "calling one I get: ". $a->one()."\n\n";
我得到以下结果:
打电话给两个我得到: Parent::two got info: results from Parent::one
打电话给我得到:结果来自 child::one
我预计上面的第一个结果是:
打电话给两个我得到: Parent::two got info: results from child::one
似乎虽然覆盖工作,但它们不会递归工作,只能在孩子的直接调用中工作。有没有办法确保当子类从父类访问方法时,父方法在存在时引用被覆盖的方法?
谢谢
解决方案
您可能正在寻找后期绑定。简单地从self::one()
to改变就static::one()
可以了。
return "Parent::two got info: ".static::one();
推荐阅读
- android - android从哪里获得补色?@color/mtrl_text_btn_text_color_selector
- android - 是否可以通过 Google Play 升级设备所有者应用程序?
- python - 为什么我的代码结果显示在调试控制台上,而通常它出现在终端上
- python-3.x - 我们是否有任何用于 python 后端代码库的打包工具(如 webpack)
- regex - 当我输入“disp VARIABLE attr stixpaths limit INT”时,正则表达式没有按预期工作
- c++ - 检查是否满足密码条件,但 Pearson Revel 说错了
- reactjs - React 正确渲染元素
- sorting - 我需要一个逻辑算法来对程序中的足球联赛数学进行排序
- azure-devops - 在新的测试计划视图中在哪里查看附件 - azure devops
- python - 在 Python 中突出显示维恩图的扇区