一尘不染

PHP中字符串的花括号

php

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


阅读 807

收藏
2020-05-26

共1个答案

一尘不染

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

复杂(卷曲)语法

之所以称其为“复杂”,是因为语法复杂,而是因为它允许使用复杂的表达式。

可以通过此语法包括具有字符串表示形式的任何标量变量,数组元素或对象属性。只需以与出现在字符串外部相同的方式编写表达式,然后将其包装在{和中即可}。由于{无法转义,因此仅在$紧随其后的才会识别此语法{。使用
{\$得到文字{$。一些示例可以使您清楚:

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

由于没有命名为的变量,根据您的错误级别,将不起作用或产生错误$aefgh,因此您需要执行以下操作:

$out = "${a}efgh"; // or
$out = "{$a}efgh";
2020-05-26