cle*_*tus 265
这是字符串插值的复杂(卷曲)语法.从手册:
复杂(卷曲)语法
这不称为复杂,因为语法很复杂,但因为它允许使用复杂的表达式.
可以通过此语法包含具有字符串表示的任何标量变量,数组元素或对象属性.只需像在字符串外部一样编写表达式,然后将其包装在
{和中}.由于{无法进行转义,因此只有在$紧随其后才能识别此语法{.使用{\$得到文字{$.一些例子说清楚:Run Code Online (Sandbox Code Playgroud)<?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";
Run Code Online (Sandbox Code Playgroud)
表现完全相同:
$out = "{$a} {$a}"; // same
Run Code Online (Sandbox Code Playgroud)
所以花括号是不必要的.但是这个:
$out = "$aefgh";
Run Code Online (Sandbox Code Playgroud)
将根据您的错误级别,无法工作或产生错误,因为没有命名的变量$aefgh,所以您需要这样做:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
Run Code Online (Sandbox Code Playgroud)
小智 46
至于我,花括号用作连接的替代,它们更快地键入并且代码看起来更清晰.请记住使用双引号(""),因为它们的内容由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
?>
Run Code Online (Sandbox Code Playgroud)
小智 14
例:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Run Code Online (Sandbox Code Playgroud)
没有花括号,PHP会尝试找到一个名为的变量$numberth,它不存在!