我对 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();
?>
http://www.php.net/manual/en/language.oop5.visibility.php
这个例子输出
Bar::testPrivate
Foo::testPublic
请您解释一下这是怎么发生的?
为什么 testPublic()
都没有被调用?
我在 Bar 类构造中放置了一个 var_dump($this)
。它打印 object(Foo)[1]
。我所知道的是可以在同一个类中调用私有(private)属性。
那么“Bar::testPrivate
”是怎么调用的呢?
最佳答案
Then how "Bar::testPrivate" is called?
当您调用 $myFoo->test()
时,它会在 Bar
的上下文中运行代码,因为 Foo
类没有不要覆盖它。
在 Bar::test()
中,当 $this->testPrivate()
被调用时,解释器将首先查看 Foo
但是该方法是私有(private)的(并且不能从 Bar
调用后代类的私有(private)方法),因此它会向上一级直到找到合适的方法;在这种情况下,它将是 Bar::testPrivate()
。
相比之下,当 $this->testPublic()
被调用时,解释器会立即在 Foo
中找到合适的方法并运行它。
编辑
why both testPublic() are not called?
当您运行 $this->testPublic()
时,只会调用一个方法,最远的一个(根据与基类的距离)。
如果 Foo::testPublic()
还需要执行父级的实现,则应在该方法中编写 parent::testPublic()
。
关于php 手动可见性示例混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12794290/