首页 > 解决方案 > 如果存在,如何让 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

似乎虽然覆盖工作,但它们不会递归工作,只能在孩子的直接调用中工作。有没有办法确保当子​​类从父类访问方法时,父方法在存在时引用被覆盖的方法?

谢谢

标签: phpoopinheritanceextends

解决方案


您可能正在寻找后期绑定。简单地从self::one()to改变就static::one()可以了。

return "Parent::two got info: ".static::one();

推荐阅读