關於類繼承的一個問題

來源:互聯網
上載者:User
下面的這段代碼:

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()方法是在父類裡面定義的,其中引用的私人方法始終都是調用父類的,不管子類裡有沒有定義與其同名的方法。

這個方法域有關,在調用Bartest方法時,phpcalling scopeFoo,所以public的方法會因為重寫被覆蓋掉,而private的方法只會依照可見度採用Bar裡的方法。

父類中的private方法子類不能重寫與調用

Foo 類雖然重寫了兩個方法,但是沒有重寫test()方法。

而執行父類的test方法時,$this是調用父類的私人方法,即父類有此私人方法,則調用父類的。父類沒有,才會用子類的。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.