我可以区分
echo "{$var1}someString" // here the variable is $var1
echo "$var1someString" // here the variable is $var1someString
问题是为什么要使用{}
?它仅适用于{}
. 它不适用于()
. 有什么特别之处{ }
?
花括号{}
以这种方式用于标识字符串中的变量:
echo "{$var1}someString"
如果你看:
echo "$var1someString"
PHP 不可能确定您想要 echo $var1
,它会将所有这些都作为变量名。
您可以改为连接变量:
echo $var1 . "someString"
它不能()
仅仅因为 PHP 设计者选择{}
.
根据string的文档,卷曲部分称为复杂语法。它基本上允许您在字符串中使用复杂的表达式。
文档中的示例:
<?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()}";
?>
你自己解释了。这就是 php 使用的语法——仅此而已。引用文档:
复杂(卷曲)语法
只需将表达式编写成与它出现在字符串外部相同的方式,然后将其包装在 { 和 }中。由于 { 无法转义,因此只有在 $ 紧跟 { 时才能识别此语法。使用 {\$ 获取文字 {$
在这里{}
定义这些变量不是一个简单的字符串,所以 php 获取该变量值而不是假设它是一个简单的字符串。