请看下面给出的代码。
<?php
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublicn";
}
private function testPrivate() {
echo "Bar::testPrivaten";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublicn";
}
private function testPrivate() {
echo "Foo::testPrivaten";
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
在上面的例子中,当我们调用$myFoo->test();
时,它调用testPrivate
Bar class
但是为什么它被称为Foo
类的testPublic
。
任何人都可以在这方面帮助我吗?
Bar.testPrivate
和Foo.testPrivate
必须是受保护的方法,而不是私有方法。 请参阅此处了解更多信息:
http://php.net/manual/en/language.oop5.visibility.php
因为 test() 不在 Foo 中,而是在 Bar 范围内运行。酒吧范围无法访问 Foo 私有方法。只需将 test() 添加到 Foo...
事实上,可见性页面上的评论之一确实重申了这一点:
"私有方法从不参与重写,因为这些方法在子类中不可见。"
这确实感觉有点奇怪,因为您会认为子类会覆盖方法名称相同的父类,但私有方法并非如此,父方法在这里占主导地位,因此如果您想覆盖,最好使用受保护的方法。