[英]Yii how to call function recursively
如何遞歸調用test()
? 我嘗試了兩種方式,但沒有成功。
namespace app\controllers;
use Yii;
use yii\web\Controller;
class SiteController extends Controller {
public function actionIndex() {
$test= $this->test(5);
}
return $this->render('index');
}
private function test($res) {
$test1 = parent::test(1);
$test2 = $this->test(1);
}
}
我嘗試用$test1 = parent::test(1);
AND $test2 = $this->test(1);
。
語法錯誤
public function actionIndex() {
$test= $this->test(5);
} //<--- this should not be here as it closes the actionIndex method
return $this->render('index');
}
這將引發unexpected T_RETURN
解析錯誤。
這是
<b>Parse error</b>: syntax error, unexpected 'return' (T_RETURN), expecting function (T_FUNCTION) or const (T_CONST) in
另外,您可能無法從子級調用父級測試方法,因為它是私有的,並且只能從聲明它的類中訪問私有方法。 即使使用parent
,也無法將范圍解析為它。 我可以想到的唯一方法是使用反射(特別是ReflectionMethod),然后將其設置為可訪問性。 但是,那將被認為是一個非常丑陋的hack。
class foo{
private function test($var){
echo $var;
}
}
class bar extends foo{
public function actionIndex($var){
$this->test($var);
}
private function test($var){
$R = new ReflectionMethod(parent::class, 'test');
$R->setAccessible(true);
$R->invoke(new parent, $var);
//$this->test($var); //recursive
}
}
(new bar)->actionIndex('Hello from parent');
輸出量
Hello from parent
您將遇到的問題是,您需要一個parent實例來調用該方法,而您沒有該方法,調用new
將丟失子對象的任何狀態。 因此,子級中設置的任何屬性都不會轉移,即使它們是在父級中定義的(除非它們是在構造函數中設置的)也是如此。
要使其具有遞歸性,只需在反射部分后面的子方法中添加$this->test()
。 當然,這將產生無限循環,但無論如何。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.