简体   繁体   English

PHP中的花括号符号

[英]Curly Braces Notation in PHP

I was reading source of OpenCart and I ran into such expression below. 我正在阅读OpenCart的源代码,并且在下面遇到了这种表达。 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. 对我来说,这似乎是一个对象,但我不确定。

Curly braces are used to denote string or variable interpolation in PHP. 花括号用于表示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: 使用此方法,可以像在数组上一样在对象上创建属性:

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

Or you can call one of a set of methods, if you have some sort of REST API class: 或者,如果您具有某种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();
}

It's also used in strings to more easily identify interpolation, if you want to: 如果要执行以下操作,还可以在字符串中使用它来更轻松地识别插值:

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

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']的值运行许多函数之一。

The name of the property is computed during runtime from two strings 该属性的名称是在运行时根据两个字符串计算得出的

Say, $result['code'] is 'abc' , the accessed property will be 假设$result['code']'abc' ,则访问的属性为

$this->model_shipping_abc

This 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: 否则,将无法区分以下内容:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM