我对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).它打印对象(Foo)[1].我所知道的是私有属性可以用同一个类调用.
然后如何调用“Bar :: testPrivate”?
Then how “Bar::testPrivate” is called?
当你调用$myFoo-> test()时,它会在Bar的上下文中运行代码,因为Foo类没有覆盖它.
在Bar :: test()内部,当$this-> testPrivate()被调用时,解释器将首先查看Foo,但该方法是私有的(并且无法从Bar调用后代类的私有方法),所以它达到一级,直到找到合适的方法;在这种情况下,将是Bar :: testPrivate().
相反,当调用$this-> testPublic()时,解释器会立即在Foo中找到合适的方法并运行它.
编辑
why both testPublic() are not called?
运行$this-> testPublic()时,只调用一个方法,最远的一个(就基于距基类的距离而言).
如果Foo :: testPublic()还需要执行父实现,那么应该在该方法中编写parent :: testPublic().