【问题标题】:How and why use curly braces: return $this->{$this->action}();如何以及为什么使用花括号: return $this->{$this->action}();
【发布时间】:2015-02-24 03:54:23
【问题描述】:

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

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

以及方法executeAction代码:

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

我的问题是这行代码:$this->{$this->action}() 这个方法是如何被调用的,为什么要使用花括号;是否正在尝试执行扩展类的action(); 函数?

【问题讨论】:

    标签: php function class methods


    【解决方案1】:
    $this->{$this->action}();
    

    表示应该调用的方法来自属性$this->action

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

    相当于:

    $this->func1();
    

    有关更多示例,请参阅variable variablesvariable functions 的 PHP 文档。大括号是必需的,因为$this->$this->action() 通常会被视为($this->$this)->action()

    【讨论】:

    • 是的,在某种程度上可以正常工作,但这是我第一次看到这种使用 Accolades 和 () 的实现,我对这部分很感兴趣{}();
    • 我还是不明白你说的 accolades 是什么意思。这个词的意思是奖励,和编程没有任何关系。
    • {} = 花括号,() = 括号,[] = 方括号。
    【解决方案2】:

    您可以简单地将$this->action 放在另一个局部变量中,然后调用它:

    $action = $this->action;
    $this->$action();
    

    【讨论】:

    • 是的!是一样的,但是不知道方法是怎么调用的
    • 什么意思?你能稍微解释一下“方法是如何被调用的”吗?
    • 在此代码中,在父代之前使用了荣誉{}(); 不像functions 被制成(){} 更像是Javascript ({})()。而且我不知道如何命名它,看它的父代,更像是一个函数
    • 是的,花括号我的意思是:荣誉,
    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 2013-01-29
    • 2013-12-28
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    相关资源
    最近更新 更多