PHP中,$this在继承关系中为何无法访问子类重新定义的私有方法?

php中,$this在继承关系中为何无法访问子类重新定义的私有方法?

php中$this在继承中的困境

在php中,$this变量指向当前对象的实例。在继承关系中,子类对象可以继承父类的所有公有和保护的属性和方法,但私有成员则无法被继承。

然而,在某些情况下,子类对象看似可以访问父类的私有方法,这让人感到困惑。如以下代码所示:

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小毛驴";    }}$super = new super();echo $super->printtest();echo '------------------------------------'.php_eol;$child = new child();echo $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()方法,而是调用了父类的私有方法printhello()?

原因在于php的静态绑定机制。在php中,私有方法的调用在编译时就决定了,并且永远指向父类的实现,无论子类是否重新定义了该方法。换句话说,$this->printhello()在编译时就被替换为父类的printhello()方法,因此子类无法覆盖它。

因此,在调用私有方法时,子类对象本质上访问的是父类的私有方法,即使该方法在子类中重新定义。

以上就是PHP中,$this在继承关系中为何无法访问子类重新定义的私有方法?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1248742.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月9日 20:45:46
下一篇 2025年12月8日 13:55:55

相关推荐

发表回复

登录后才能评论
关注微信