Yii如何递归调用函数

时间:2018-08-30 20:56:38

标签: php recursion yii2 yii2-basic-app

如何递归调用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);$test2 = $this->test(1);

1 个答案:

答案 0 :(得分:-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的解析错误。

Sandbox

  <b>Parse error</b>:  syntax error, unexpected 'return' (T_RETURN), expecting function (T_FUNCTION) or const (T_CONST) in

您也可能无法从子级调用父级测试方法,因为它是私有的,并且只能从声明该子级的类中访问私有方法。即使使用parent,您也无法解决其范围。我可以想到的唯一方法是使用反射(特别是ReflectionMethod),然后将其设置为可访问性。但是,那将被认为是非常丑陋的入侵。

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

Sandbox

您将遇到的问题是,您需要一个 parent 实例来调用您没有的方法,并调用new将会丢失任何状态子对象。因此,即使在父级中定义了属性,子级中设置的任何属性也不会转移(除非它们是在构造函数中设置的。)这可以接受也可以不接受。

要使其递归非常容易,只需在反射部分后面的孩子的方法中添加$this->test()。当然,这会产生无限循环,但无论如何。

相关问题