dongliufa6380 2012-10-08 22:47
浏览 24
已采纳

php手动可见性示例混淆

I have confused from an example in php manual. It's about visibility. Here is the example.

class Bar {
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }
    public function testPublic() {
        echo "Bar::testPublic
";
    }
    private function testPrivate() {
        echo "Bar::testPrivate
";
    }
}
class Foo extends Bar {
    public function testPublic() {
        echo "Foo::testPublic
";
    }
    private function testPrivate() {
        echo "Foo::testPrivate
";
    }
}
$myFoo = new foo();
$myFoo->test();  
?>

http://www.php.net/manual/en/language.oop5.visibility.php

This example outputs

Bar::testPrivate 
Foo::testPublic

Please can you explain how this happen?

why both testPublic() are not called?

I put a var_dump($this) in Bar class construct. It prints object(Foo)[1]. The thing I know is private properties can be called withing same class.

Then how "Bar::testPrivate" is called?

展开全部

  • 写回答

6条回答 默认 最新

  • dongquanjie9328 2012-10-08 22:56
    关注

    Then how "Bar::testPrivate" is called?

    When you call $myFoo->test(), it runs the code in the context of Bar because the Foo class didn't override it.

    Inside Bar::test(), when $this->testPrivate() gets called, the interpreter will look at Foo first but that method is private (and private methods from descendent classes can't be called from Bar), so it goes one level up until it can find a suitable method; in this case that would be Bar::testPrivate().

    In contrast, when $this->testPublic() gets called, the interpreter immediately finds a suitable method in Foo and runs it.

    Edit

    why both testPublic() are not called?

    Only one method gets called when you run $this->testPublic(), the furthest one (in terms of distance to the base class).

    If Foo::testPublic() needs to also execute the parent's implementation, you should write parent::testPublic() inside that method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部