19

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

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

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

4

3 回答 3

34

花括号用于表示 PHP 中的字符串或变量插值。它允许您创建“变量函数”,这可以让您在不明确知道它实际上是什么的情况下调用函数。

使用它,您可以像创建数组一样在对象上创建属性:

$property_name = 'foo';
$object->{$property_name} = 'bar';
// same as $object->foo = 'bar';

或者,如果您有某种 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();
}

如果您愿意,它还用于字符串中以更轻松地识别插值:

$hello = 'Hello';
$result = "{$hello} world";

当然,这些都是简化。您的示例代码的目的是根据$result['code'].

于 2012-01-29T19:38:19.363 回答
10

属性的名称是在运行时从两个字符串计算出来的

$result['code']is 'abc',访问的属性将是

$this->model_shipping_abc

如果您的属性或方法名称中有奇怪的字符,这也很有帮助。

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

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

$a = new A();
echo $a->f . 'unc'; // "func"
echo $a->{'f' . 'unc'}; // "uiae"
于 2012-01-29T19:26:29.517 回答
4

花括号用于显式指定变量名的结尾。

https://stackoverflow.com/a/1147942/680578

http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

于 2012-01-29T19:26:26.667 回答