[英]PHP - Call a parent function from a parent function in a child instance
A類的bar函數需要調用A類的foo函數。 對於 A 的實例, $this->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();
(...)
}
}
我為'A' bar 函數嘗試了這樣的解決方法,但收到錯誤:“當當前類范圍沒有父級時,無法訪問父級::”
class A{
function bar(){
switch ( get_class($this) )
{
case "A" : $this->foo() ; break;
case "B" : parent::foo(); break;
}
}
}
知道如何做到這一點嗎?
謝謝
你不能用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.