“{var1} someString”和“$ var1someString”之间有什么区别?

时间:2012-04-27 06:47:42

标签: php variables

我可以弄清楚

之间的区别
echo "{$var1}someString" // here the variable is $var1
echo "$var1someString"   // here the variable is $var1someString

问题是为什么要使用{}?它仅适用于{}。它不适用于(){ }有什么特别之处?

4 个答案:

答案 0 :(得分:4)

花括号{}以这种方式用于识别字符串中的变量:

echo "{$var1}someString"

如果你看一下:

echo "$var1someString"

PHP无法确定您想要回显$var1,它会将所有内容作为变量名称。

您可以改为连接变量:

echo $var1 . "someString"

它不适用于(),因为PHP设计人员选择{}

答案 1 :(得分:1)

你自己解决了这个问题。这就是php用于此的语法 - 仅此而已。引用the documentation

  

复杂(卷曲)语法
  只需以与字符串外部相同的方式编写表达式,然后将其包装在{和} 中。由于{无法转义,因此仅当$紧跟{时,才会识别此语法。使用{\ $获取文字{$

答案 2 :(得分:1)

根据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()}";
?>

答案 3 :(得分:0)

这里{}定义了这些中的变量不是一个简单的字符串,因此php将该变量值写入,而不是假设它是一个简单的字符串。