【问题标题】:What does brackets like {variable}(variable|array) statement means in php?像{variable}(variable|array)语句这样的括号在php中是什么意思?
【发布时间】:2026-01-30 14:20:05
【问题描述】:

我无法用谷歌搜索这个。问题;

public function processAPI() {
    if (method_exists($this, $this->endpoint)) {
        return $this->_response($this->{$this->endpoint}($this->args));
    }
    return $this->_response("No Endpoint: $this->endpoint", 404);
}

考虑$endpoint 是一个变量,$args 是一个类的数组。我们想将变量$this->{$this->endpoint}($this->args) 传递给_response() 方法。 php语法中{$this->endpoint}($this->args)是什么意思?

代码完整定义链接:http://coreymaynard.com/blog/creating-a-restful-api-with-php/

【问题讨论】:

标签: php syntax brackets curly-braces


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

分而治之:

$this->_response()

表示用参数调用当前对象的_response()方法

$this->{$this->endpoint}($this->args)

花括号在这里解释:http://php.net/manual/en/language.types.string.php

任何标量变量、数组元素或带有字符串的对象属性 可以通过此语法包含表示。简单地写 表达方式与它出现在字符串之外的方式相同,并且 然后将其包装在 { 和 } 中。由于 { 无法转义,因此此语法将 仅当 $ 紧跟 { 时才被识别。使用 {\$ 来 得到一个字面量 {$.

因此 {$this->endpoint} 计算为一个字符串,该字符串之前设置为当前对象的端点属性。

$this->endpointproperty($this->args)

当前对象中必须有一个方法端点属性,它接受一个参数。这个参数也是这个对象的一个​​属性:

$this->args

【讨论】:

  • 这意味着我可以调用它的名称在我的 $endpoint 变量中的方法。如果 api 调用类似于“.../cars/mercedes/2015”,这意味着我有一个 cars() 方法,并且我正在将 ['mercedes,'2015'] 数组传递给它。我的天啊。谢谢。