The bar function of the A class needs to call the foo function of the A class. For an instance of A, $this->bar() works. For an instance of B, $this->bar() doesn't work, it creates a loop B-foo - A-bar...
class A {
function foo() {
(...)
}
function bar() {
$this->foo();
(...)
}
}
class B extends A {
function foo() {
parent::bar();
(...)
}
function bar() {
$this->foo();
(...)
}
}
I tried such workaround for the 'A' bar function, but getting error : "Cannot access parent:: when current class scope has no parent"
class A{
function bar(){
switch ( get_class($this) )
{
case "A" : $this->foo() ; break;
case "B" : parent::foo(); break;
}
}
}
Any idea of how to do this?
Thanks
You cann use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.