简体   繁体   中英

Yii how to call function recursively

How can I call recursively test() ? I tried both ways and it didn't work.

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);
    }

}

I tried with $test1 = parent::test(1); AND $test2 = $this->test(1); .

Syntax error

public function actionIndex() {

    $test= $this->test(5);

    } //<--- this should not be here as it closes the actionIndex method
    return $this->render('index');
}

This will throw something like unexpected T_RETURN parse error.

Sandbox

And it's

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

Also you probably cant call the parents test method from the child because its private and you can only access a private method from within the class that declares it. Even when using parent you can't resolve the scope to it. The only way I can think to call it is to use reflection (specifically ReflectionMethod) and then set the accessibility of it to. That would be considered a pretty ugly hack though.

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');

Output

Hello from parent

Sandbox

The problem you will have with this is you need an instance of parent to invoke the method on, which you don't have and calling new you will lose any state of the child object. So any properties set in the child wont transfer, even if they are defined in the parent (unless they are set in the constructor etc.) This may or may not be acceptable.

To make it recursive is fairly easy just add, $this->test() in the child's method after the reflection part. Of course that will produce an infinite loop, but whatever.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM