PHP中字符串中的大括号

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


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

复杂(卷曲)的语法

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

任何具有字符串表示的标量变量,数组元素或对象属性均可通过此语法包含在内。 简单地写出表达式的方式与字符串外部的方式相同,然后将其包装在{} 。 由于{不能被转义,这个语法只有在$紧跟在{才能被识别。 使用{$获取文字{$ 。 一些例子要说清楚:

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

对我来说,花括号可以代替拼接,它们键入更快,代码看起来更干净。 请记住使用双引号(“”),因为它们的内容由PHP解析,因为在单引号('')中,您将获得提供的变量的字面名称:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>

例:

$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";

如果没有大括号,PHP会尝试查找名为$numberth的变量,该变量不存在!

链接地址: http://www.djcxy.com/p/1867.html

上一篇: Curly braces in string in PHP

下一篇: curly braces/no curly braces?