在PHP中,使用大括号 {} 代替双引号 "" 来解释字符串的区别是什么?

5

我阅读了PHP手册,但没有清楚说明有何不同之处。我对于为什么要使用这个东西感到困惑:

echo "Print this {$test} here.";

与此相比:

echo "Print this $test here.";
2个回答

4

来自PHP.net

复杂(花括号)语法

这并不是因为语法复杂,而是因为它允许使用复杂表达式。

任何具有字符串表示的标量变量、数组元素或对象属性都可以通过此语法包含在内。只需像在字符串外部一样编写表达式,然后将其用{和}括起来即可。由于{无法被转义,因此只有在$紧随其后时才能识别此语法。使用{\$}可以获得一个字面的{$}。

示例:

<?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()}";
?>

请查看该页面以获取更多示例。


4
在您的示例中,没有区别。但是,当变量表达式更加复杂时,例如带有字符串索引的数组,使用花括号会更有帮助。例如:
$arr['string'] = 'thing';

echo "Print a {$arr['string']}";
// result: "Print a thing";

echo "Print a $arr['string']";
// result: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接