繁体   English   中英

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

[英]php variable parsing in double quoted strings

在阅读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是一个对象。 我只是不知道这些例子的前身代码是什么。 任何帮助都会有用。

让我们使用您提供的手册中的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的值,即“变量值”。

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

以下是您发布的示例,

使用{}请确保评估对象的整个路径。 如果删除它们,它将只评估返回Array $obj->values

$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]

在前两个示例中,首先评估$name ,然后保留{$ mike}。 由于您在新变量名称之外有花括号,因此也将对此进行评估,并将转换为字符串Michael 在最后一个例子中,你将留下$mike

$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

此示例与上面的示例类似,但不使用变量$ name,而是使用函数。 如果在函数周围没有花括号{} (例如#2),但是在$getName() ,PHP将尝试访问function $getName ,这不是合法的函数名。 最后一个示例$ getName()将获取变量$ getName的值,而()将保持不变。 所以,如果你有$getName = "Heya"; ,它会成为Heya()

function getName() { return "mike"; }
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(): Michael
echo "This is the value of the var named by the return value of getName(): {$getName()}";  // Fatal error: Function name must be a string
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(): ()

暂无
暂无

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

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