如何以及为何使用大括号: return $this->{$this->action}();

Rob*_*Dan 3 php methods class function

所以在第一部分中我创建了 2 个对象,实例化两个类(我们从 createController 函数生成一个类)

$loader = new Loader(); 
$controller = $loader->createController(); 
$controller->executeAction();
Run Code Online (Sandbox Code Playgroud)

和方法executeAction代码:

public function executeAction() {
    return $this->{$this->action}();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是采用这行代码:$this->{$this->action}()如何调用此方法以及为什么使用花括号;是否尝试执行action();扩展类的功能?

Bar*_*mar 5

$this->{$this->action}();
Run Code Online (Sandbox Code Playgroud)

意味着应该调用的方法来自 property $this->action

$this->action = 'func1';
$this->{$this->action}();
Run Code Online (Sandbox Code Playgroud)

相当于:

$this->func1();
Run Code Online (Sandbox Code Playgroud)

有关更多示例,请参阅可变变量可变函数的 PHP 文档。需要大括号,因为$this->$this->action()通常会被视为($this->$this)->action().