
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在继承关系中为何无法访问子类重新定义的私有方法?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号