PHP手册OOP可见性示例 – 有人可以解释它
发布时间:2020-12-13 14:10:04 所属栏目:PHP教程 来源:网络整理
导读:我在 PHP OOP手册 http://www.php.net/manual/en/language.oop5.visibility.php中看到了这个,我无法理解为什么输出不是:Foo :: testPrivate Foo :: testPublic class Bar { public function test() { $this-testPrivate(); $this-testPublic(); } public fu
我在
PHP OOP手册
http://www.php.net/manual/en/language.oop5.visibility.php中看到了这个,我无法理解为什么输出不是:Foo :: testPrivate Foo :: testPublic
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
这完全取决于变量/方法的可见性.
您会注意到在Bar类中,方法testPrivate()是私有的.这意味着ONLY本身可以访问该方法.没有小孩. 所以当Foo扩展Bar,然后要求运行test()方法时,它会做两件事: >它覆盖了testPublic()方法,因为它是公共的,并且Foo有权使用它自己的版本覆盖它. testPrivate()没有被重写,并且是包含test()的类的一部分.因此,打印了Bar :: testPrivate.testPublic()被重写,并且是继承类的一部分.因此,打印Foo :: testPublic. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |