我很难理解为什么我们会得到这段代码的输出:
<?php
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test();
?>
所以 Foo 扩展了 Bar。 $myfoo 是类 Foo 的对象。 Foo 没有名为 test() 的方法,因此它从其父 Bar 扩展它。但是为什么test()的结果是
Bar::testPrivate
Foo::testPublic
当这个父类的方法在子类中被覆盖时,你能解释一下为什么第一个不是 Foo::testPrivate 吗?
非常感谢您!
最佳答案
可能是因为 testPrivate
顾名思义,是一个私有(private)方法,不会被类继承继承/覆盖。
在 php.net 手册页上,您可能从中得到的代码明确指出 We can redeclare the public and protected method, but not private
因此,具体发生的情况如下:子类不会重新声明方法 testPrivate
而是在“作用域”中创建它自己的版本(如果只有子对象)。由于 test()
定义在父类中,它将访问父类 testPrivate
。
如果您要在子类中重新声明test
函数,它应该访问childs? testPrivate()
方法。
关于php - 继承和可见性 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13044281/