PHP子类如何调用父类私有方法?
时间:2025-03-19
浏览:410
作者:佚名
本文探讨PHP继承机制下子类调用父类私有方法的难题。由于PHP私有方法的静态绑定机制,子类无法直接访问父类私有方法。即使子类重写了同名方法,当父类方法内部调用私有方法时,子类调用父类方法仍会执行父类中已绑定的私有方法,而非子类方法。文章通过代码示例及详细解释,阐明了这种机制与Java静态绑定的相似性,并解答了子类调用父类方法时,为何执行的是父类私有方法的疑惑。 学习本文,助您深入理解PHP继承与私有方法的特性,避免潜在的代码陷阱。

PHP继承、$this关键字与私有方法调用
本文分析PHP继承机制中$this关键字与私有方法调用的关联,解释子类无法直接访问父类私有方法,但父类方法内部调用私有方法时,子类调用父类方法的行为。
问题:
以下代码中,父类super包含私有方法printhello()和公有方法printtest()。printtest()调用printhello()并打印当前类名。子类child也定义了printhello()方法。调用printtest()的结果并非预期。
<?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小毛驴";
}
}
$super = new super();
echo $super->printtest();
echo '------------------------------------' . PHP_EOL;
$child = new child();
echo $child->printtest();
?>
输出:
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私有方法的绑定机制。PHP私有方法在编译时进行静态绑定。$this->printhello()在编译阶段被父类super的printhello()方法直接替换。即使子类存在同名方法,也无法改变这一绑定。 这与Java的静态绑定类似,虽然PHP没有明确的“静态绑定”说法,但底层机制相似。
因此,子类无法直接访问父类私有方法,但如果父类方法内部调用了私有方法,子类实例调用父类方法时,仍然会执行父类中静态绑定的私有方法。
以上就是《PHP子类如何调用父类私有方法?》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
