2012-04-23 23 views

回答

4

在你的例子中,沒有區別。但是,當變量表達式更復雜時,這非常有用,例如具有字符串索引的數組。例如:

$arr['string'] = 'thing'; 

echo "Print a {$arr['string']}"; 
// result: "Print a thing"; 

echo "Print a $arr['string']"; 
// result: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE 
+0

啊,我非常感謝你。 – Andy 2012-04-23 18:34:50

4

PHP.net

複合物(花)語法

這不稱爲複雜,因爲語法很複雜,但由於它允許使用複雜的表達式納秒。

任何具有字符串 表示的標量變量,數組元素或對象屬性都可以通過此語法包含在內。只需使用與字符串外部相同的方式編寫 表達式,然後 將其包裝在{和}中。由於{不能被轉義,這個語法將只在$緊跟在{之後纔會被識別出來, 。使用{\ $到 獲得一個文字{$。

實施例:

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

請參閱頁更多的例子。