下面的這段代碼:
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 ();
輸出為什麼是
Bar::testPrivate Foo::testPubli
而不是
Foo::testPrivate Foo::testPubli
回複內容:
下面的這段代碼:
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 ();
輸出為什麼是
Bar::testPrivate Foo::testPubli
而不是
Foo::testPrivate Foo::testPubli
Foo類裡的testPublic()方法重寫了父類Bar的testPublic();
而testPrivate()的屬性是private,只能被同一個類對象訪問,哪怕不是同一個執行個體,既然只能被同一個類對象訪問,那肯定也不會被重寫,所以才會出現上面的輸出
私人方法不會被繼承,所以由於test()
方法是在父類裡面定義的,其中引用的私人方法始終都是調用父類的,不管子類裡有沒有定義與其同名的方法。
這個方法域有關,在調用Bar
的test
方法時,php
的calling scope
是Foo
,所以public
的方法會因為重寫被覆蓋掉,而private
的方法只會依照可見度採用Bar
裡的方法。
父類中的private方法子類不能重寫與調用
Foo 類雖然重寫了兩個方法,但是沒有重寫test()方法。
而執行父類的test方法時,$this是調用父類的私人方法,即父類有此私人方法,則調用父類的。父類沒有,才會用子類的。