【问题标题】:late static binding | without modifying parent class with `static` keyword后期静态绑定|无需使用 `static` 关键字修改父类
【发布时间】:2012-12-25 17:36:39
【问题描述】:

我有以下父子类。

class Parent_class {

    protected static function method_one() {
        echo "I am in Parent_class in method_one";
    }

    protected function execute() {
        static::method_one();
    }

    public function start() {
        $this->execute();
    }

}

class Child_class extends Parent_class {

    protected static function method_one() {
        echo "I am in Child_class in method_one";
    }

}

$obj = new Child_class();
$obj->start();

Result - it is calling Child class method.

结果与预期一致,因为 php5.3 支持静态后期绑定,已保留关键字 static

但问题是,我没有对 Parent 类的写入权限,因此在调用 methode_one 时我不能使用 static,因此它没有执行后期静态绑定。

有什么方法可以访问覆盖方法吗?

父类是一个定义好的库,我不能修改它。

出路是修改父类或完全放弃这个想法,但你能提出其他替代方案吗?

【问题讨论】:

    标签: php late-static-binding


    【解决方案1】:

    为什么不在子类中实现执行或启动?

    【讨论】:

    • 感谢评论,在这种情况下,我需要复制执行方法的代码,然后在需要时将 self 更改为 static,但这是一种好的编程习惯吗?如果将来有人更改父类怎么办。
    • 同意..所以你需要看看它是否值得
    • 或者我可以根据您的建议覆盖这两种方法,然后我将在我的函数本身的第一行调用父函数.. 可能有效:)
    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 2011-02-12
    • 2019-01-16
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多