How and why use curly braces: return $this->{$this

2019-02-26 05:11发布

so in first part i made 2 object, instantiate two classes (one we generate from createController function)

$loader = new Loader(); 
$controller = $loader->createController(); 
$controller->executeAction();

and the method executeAction code:

public function executeAction() {
    return $this->{$this->action}();
}

my question is taking this line of code: $this->{$this->action}() how this method is called and why use curly braces; Is trying to execute the action(); function of extended class maybe?

2条回答
霸刀☆藐视天下
2楼-- · 2019-02-26 05:38

You can simply put the $this->action in another local variable and then, call it:

$action = $this->action;
$this->$action();
查看更多
Rolldiameter
3楼-- · 2019-02-26 05:56
$this->{$this->action}();

means that the method that should be called comes from the property $this->action.

$this->action = 'func1';
$this->{$this->action}();

is equivalent to:

$this->func1();

See the PHP documentation of variable variables and variable functions for more examples of this. The braces are needed because $this->$this->action() would normally be treated as ($this->$this)->action().

查看更多
登录 后发表回答