[英]PHP - Call a parent function from a parent function in a child instance
The bar function of the A class needs to call the foo function of the A class. A类的bar函数需要调用A类的foo函数。 For an instance of A, $this->bar() works.对于 A 的实例, $this->bar() 有效。 For an instance of B, $this->bar() doesn't work, it creates a loop B-foo - A-bar...对于 B 的实例, $this->bar() 不起作用,它会创建一个循环 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"我为'A' bar 函数尝试了这样的解决方法,但收到错误:“当当前类范围没有父级时,无法访问父级::”
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
你不能用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.