用双引号字符串解析php变量

时间:2014-08-12 23:57:27

标签: php string

在阅读php手册中双引号字符串中的变量解析时,我遇到了两个令我困惑的例子。一个如何使用某些代码的示例将有很大帮助。以下是手册中的代码:

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

这究竟是什么意思?我知道$obj是一个对象。我只是不知道这些例子的前身代码会是什么。任何帮助都会有用。

2 个答案:

答案 0 :(得分:3)

让我们使用您提供的手册中的3个示例。

我们可以为这些变量提供一个名称,并查看输出以查看它们的作用。

$obj->values[3]->name = "Object Value";
$name = "variable";
$variable = "Variable Value"; // You'll see why we need to define this in a minute
$function = "Function Value";
function getName() {
    return "function";
}

我想你已经看到了这种情况,但让我们看看这对你发表的陈述意味着什么:

echo "This works too: {$obj->values[3]->name}"; // This works too: Object Value

echo "This is the value of the var named $name: {${$name}}"; // This is the value of the var named $name: Variable Value

echo "This is the value of the var named by the return value of getName(): {${getName()}}"; // This is the value of the var named by the return value of getName(): Function Value

在第一种情况下,它用"对象值替换对象值。"

在第二个$name被解释为"变量",这意味着{${$name}}被解释为$variable的值,即"变量值"

同样的原则适用于函数的返回值。

答案 1 :(得分:0)

以下是您发布的示例

使用{}时,请确保评估对象的整个路径。如果您将其删除,则只评估返回$obj->values的{​​{1}}。

Array

在前两个示例中,首先评估$obj->values[3] = "Name"; echo "This works too: {$obj->values[3]}"."\n"; // CORRECT: This works too: Name echo "This works too: $obj->values[3]"."\n\n"; // ERROR: This works too: Array[3] ,然后留下{$ mike}。由于您在新变量名称之外有花括号,因此也会对此进行评估,并将转换为字符串$name。在最后一个示例中,您将留下Michael

$mike

此示例与上面的示例类似,但不使用变量$ name,而是使用函数。如果您在函数周围没有大括号$name = "mike"; $mike = "Michael"; echo "This is the value of the var named $name: {${$name}}"."\n"; // This is the value of the var named mike: Michael echo "This is the value of the var named $name: {$$name}"."\n"; // This is the value of the var named mike: Michael echo "This is the value of the var named $name: $$name"."\n\n"; // This is the value of the var named mike: $mike (示例#2),但在{}周围,PHP将尝试访问$getName(),这不是合法的函数名称。 最后一个示例$ getName()将获取变量$ getName的值,而()将保持不变。因此,如果您有function $getName,它将变为$getName = "Heya";

Heya()