PHP中的卷曲括号表示法

Tar*_*rik 16 php curly-braces

我正在阅读OpenCart的源代码,我在下面遇到了这样的表达.有人可以向我解释一下:

$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
Run Code Online (Sandbox Code Playgroud)

在声明中,有一个奇怪的代码部分,
$this->{'model_shipping_' . $result['code']}
它有{},我不知道那是什么?它看起来像我的对象,但我不是很确定.

mrl*_*lee 28

大括号用于表示PHP中的字符串或变量插值.它允许您创建"变量函数",这可以让您在不明确知道实际内容的情况下调用函数.

使用它,您可以在对象上创建一个类似于数组的属性:

$property_name = 'foo';
$object->{$property_name} = 'bar';
// same as $object->foo = 'bar';
Run Code Online (Sandbox Code Playgroud)

或者,如果您有某种REST API类,则可以调用其中一组方法:

$allowed_methods = ('get', 'post', 'put', 'delete');
$method = strtolower($_SERVER['REQUEST_METHOD']); // eg, 'POST'

if (in_array($method, $allowed_methods)) {
    return $this->{$method}();
    // return $this->post();
}
Run Code Online (Sandbox Code Playgroud)

它也用于字符串,以便更容易识别插值,如果你想:

$hello = 'Hello';
$result = "{$hello} world";
Run Code Online (Sandbox Code Playgroud)

当然这些都是简化.示例代码的目的是根据值运行许多函数中的一个$result['code'].


kni*_*ttl 10

在运行时期间,从两个字符串计算属性的名称

比如说,$result['code']'abc'访问的属性将是

$this->model_shipping_abc
Run Code Online (Sandbox Code Playgroud)

如果您的属性或方法名称中包含奇怪的字符,这也很有用.

否则就无法区分以下内容:

class A {
  public $f = 'f';
  public $func = 'uiae';
}

$a = new A();
echo $a->f . 'unc'; // "func"
echo $a->{'f' . 'unc'}; // "uiae"
Run Code Online (Sandbox Code Playgroud)