2017-04-13 79 views
1

A類的bar函數需要調用A類的foo函數。 對於A的一個實例,$ this-> bar()起作用。 對於B的情況下,這 - $>巴()不工作,它創建了一個環路B-FOO - A-吧...PHP - 在子實例中調用父函數的父函數

class A { 
    function foo() { 
     (...) 
    } 
    function bar() { 
     $this->foo(); 
     (...) 
    } 
} 
class B extends A { 
    function foo() { 
     parent::bar(); 
     (...) 
    } 
    function bar() { 
     $this->foo(); 
     (...) 
    } 
} 

我想這樣的解決方法爲 'A' 酒吧函數,但得到錯誤:「噹噹前類作用域沒有父代時不能訪問父::」

class A{ 
    function bar(){ 
     switch (get_class($this)) 
     { 
      case "A" : $this->foo() ; break; 
      case "B" : parent::foo(); break; 
     } 
    } 
} 

任何想法如何做到這一點?

感謝

+0

'自:: foo的();''在A'? – JustOnUnderMillions

回答

1

你卡恩使用self

class A { 
    function foo() { 
     print __METHOD__; 
    } 
    function bar() { 
     print __METHOD__; 
     self::foo(); 
    } 
} 
class B extends A { 
    function foo() { 
     print __METHOD__; 
     parent::bar(); 
    } 
    function bar() { 
     print __METHOD__; 
     $this->foo(); 
    } 
} 
(new A)->bar();//calls A::bar A::foo 
(new A)->foo();//calls A::foo 
(new B)->bar();//calls B::bar B::foo A::bar A::foo 
(new B)->foo();//calls B::foo A::bar A::foo