PHP继承中,子类如何调用父类的私有方法?

php继承中,子类如何调用父类的私有方法?

PHP继承与私有方法调用:$this关键字的深入探讨

本文分析PHP继承机制中$this关键字与私有方法的交互,重点关注子类如何(或不能)调用父类的私有方法。

以下代码演示了一个父类Super和子类Child。父类包含私有方法printHello()和公有方法printTest(),后者调用前者。子类Child也定义了一个公有方法printHello()。

<?php
class Super {
    private function printHello() {
        echo get_called_class() . ' hello' . PHP_EOL;
    }

    public function printTest() {
        var_dump(get_class($this));
        var_dump(get_class_methods($this));
        $this->printHello();
    }
}

class Child extends Super {
    public function printHello() {
        echo "阿凡提de小毛驴" . PHP_EOL;
    }
}

$super = new Super();
$super->printTest();
echo '------------------------------------' . PHP_EOL;
$child = new Child();
$child->printTest();
登录后复制

运行结果:

立即学习PHP免费学习笔记(深入)”;

string(5) "Super"
array(2) {
  [0] => string(10) "printHello"
  [1] => string(9) "printTest"
}
Super hello
------------------------------------
string(5) "Child"
array(2) {
  [0] => string(10) "printHello"
  [1] => string(9) "printTest"
}
Child hello
登录后复制

结果显示,$child->printTest()仍然调用了父类的printHello(),而非子类方法。 这并非因为子类无法访问父类私有方法,而是PHP私有方法的静态绑定机制导致的。在编译阶段,对私有方法的调用会被其函数体直接替换。 这与Java的静态绑定类似,PHP底层可能也采用了类似机制。 因此,即使在子类中调用$this->printHello(),实际执行的仍然是父类中定义的printHello()方法。 换句话说,PHP在编译时就确定了$this->printHello()指向哪个方法。

因此,子类无法直接调用父类的私有方法。 如果需要在子类中使用类似的功能,应该在父类中提供受保护的(protected)方法,或者使用其他设计模式来实现。

以上就是PHP继承中,子类如何调用父类的私有方法?的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1239748.html

发表回复

Your email address will not be published. Required fields are marked *