2015-04-01 56 views
1

我無法識別$ {「item_ $ i」}的PHP語法; item_ $我可以是item_1到item_6。 $ {}在作業中表示什麼?我在搜索中找不到示例。

if($cl_name=='A') $data = ${"item_$i"}; 

感謝您的幫助。

回答

2

這就是所謂的Complex (curly) syntax

這不叫複雜,因爲語法複雜,而是因爲它允許使用複雜表達式。

任何具有字符串表示形式的標量變量,數組元素或對象屬性均可通過此語法包含在內。簡單地寫出表達式的方式與字符串外部的方式相同,然後將其包裝在{和}中。由於{不能被轉義,這個語法只有在$緊跟在{之後才能被識別。使用{\ $獲取文字{$。一些例子要說清楚:

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