2017-04-13 2 views
1

Die Balkenfunktion der Klasse A muss die foo-Funktion der Klasse A aufrufen. Für eine Instanz von A funktioniert $ this-> bar(). Für eine Instanz von B, $ this-> bar() nicht funktioniert, erzeugt es eine B-foo Schleife - A-Bar ...PHP - Aufruf einer übergeordneten Funktion von einer übergeordneten Funktion in einer untergeordneten Instanz

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

ich eine solche Abhilfe für das 'A' Bar versucht Funktion, aber immer Fehler: „Kann nicht geordneten Zugriff :: wenn aktuelle Klassenbereich keine Eltern hat“

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

Irgendeine Idee, wie dies zu tun?

Dank

+0

'self :: foo();' in 'A'? – JustOnUnderMillions

Antwort

1

Sie cann Verwendung 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 
Verwandte Themen