这是字符串插值的complex (curly) syntax.从手册中:
复杂(curl )语法
这不是因为语法复杂而称为复杂,而是因为 它允许使用复杂的表达式.
任何带有字符串的标量变量、数组元素或对象属性
<?php // Show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; 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()}}"; echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; ?>
通常,此语法是不必要的.例如,这是:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
行为与此完全相同:
$out = "{$a} {$a}"; // same
所以没有必要用花括号.但是this:
$out = "$aefgh";
由于没有名为$aefgh
的变量,根据您的错误级别,将不起作用或产生错误,因此您需要执行以下操作:
$out = "${a}efgh"; // or
$out = "{$a}efgh";