PHP中的花括号符号 [英] Curly Braces Notation in PHP

查看:156
本文介绍了PHP中的花括号符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

在语句中,有一个奇怪的代码部分是
$this->{'model_shipping_' . $result['code']}
哪个有{},我想知道是什么吗?在我看来,这是一个对象,但我不确定.

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.

推荐答案

花括号用于表示PHP中的字符串或变量插值.它允许您创建变量函数",从而可以在不显式知道其实际含义的情况下调用函数.

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:

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

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

Or you can call one of a set of methods, if you have some sort of REST API class:

$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";

当然,这是简化.示例代码的目的是根据$result['code']的值运行许多功能之一.

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'].

这篇关于PHP中的花括号符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆