小编典典

PHP中字符串中的花括号

all

{ }PHP中字符串文字中的(大括号)是什么意思?


阅读 59

收藏
2022-06-22

共1个答案

小编典典

这是字符串插值的复杂(卷曲)语法。从手册:

复杂(卷曲)语法

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

任何具有字符串表示的标量变量、数组元素或对象属性都可以通过此语法包含在内。只需将表达式写成与它出现在字符串之外的相同方式,然后将其包装在{and中}。由于{无法转义,因此只有在$紧跟.
时才会识别此语法{。用于 {\$获取文字{$. 一些例子可以清楚地说明:

<?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

所以花括号是不必要的。但是 这个

$out = "$aefgh";

将根据您的错误级别,要么不起作用,要么产生错误,因为没有变量 named $aefgh,所以你需要这样做:

$out = "${a}efgh"; // or
$out = "{$a}efgh";
2022-06-22