PHP 中的大括号表示法
我正在阅读 OpenCart 的源代码,遇到了下面这样的表达式。有人可以向我解释一下吗:
$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
在声明中,有一个奇怪的代码部分是$this->{'model_shipping_' . $结果['code']}
其中有 {}
,我想知道那是什么?它对我来说看起来是一个物体,但我不太确定。
I was reading source of OpenCart and I ran into such expression below. Could someone explain it to me:
$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
In the statement, there is a weird code part that is$this->{'model_shipping_' . $result['code']}
which has {}
and I wonder what that is? It looks an object to me but I am not really sure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大括号用于表示 PHP 中的字符串或变量插值。它允许您创建“变量函数”,这可以让您在不明确知道函数实际是什么的情况下调用函数。
使用它,您可以在对象上创建属性,就像创建数组一样:
或者,如果您有某种 REST API 类,您可以调用一组方法中的一个:
它也用于字符串中,以更轻松地识别插值,如果你想:
当然这些都是简化。示例代码的目的是根据
$result['code']
的值运行多个函数之一。Curly braces are used to denote string or variable interpolation in PHP. It allows you to create 'variable functions', which can allow you to call a function without explicitly knowing what it actually is.
Using this, you can create a property on an object almost like you would an array:
Or you can call one of a set of methods, if you have some sort of REST API class:
It's also used in strings to more easily identify interpolation, if you want to:
Of course these are simplifications. The purpose of your example code is to run one of a number of functions depending on the value of
$result['code']
.属性的名称是在运行时从两个字符串计算出来的。
比如说,
$result['code']
是'abc'
,访问的属性将是这也很有帮助,如果您的属性或方法名称中有奇怪字符。
否则将无法区分以下内容:
The name of the property is computed during runtime from two strings
Say,
$result['code']
is'abc'
, the accessed property will beThis is also helpful, if you have weird characters in your property or method names.
Otherwise there would be no way to distinguish between the following:
https://stackoverflow.com/a/1147942/680578
http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex
https://stackoverflow.com/a/1147942/680578
http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex