2012-01-11 60 views
1

我想直接從函數的返回值訪問數組。如何訪問函數返回的數組的鍵值

e.g. 
$arr = find_student(); 
echo $arr['name']; 

// I want to be able to do 
echo find_student()['name'] 

我怎樣才能達到同樣的?沒有另一行代碼?

+0

你想要什麼都做不到。你必須首先給返回值賦予一個變量 – jere 2012-01-11 12:36:47

+0

等待PHP 5.4的幾個星期/幾個月(我相信)確實允許這種語法 – 2012-01-11 12:43:42

回答

6

你不行。 PHP語法解析器是有限的,不允許在當前版本中使用。

PHP devs擴展了即將發佈的PHP的解析器。這裏有一個blog talking about it

2

一個鏈接,你不能:)

function find_student() {return array('name'=>123);} 
echo find_student()['name']; 

結果: 解析錯誤:語法錯誤,意想不到的 '[',希望 '' 或 ';'

2

您可以使用ArrayObject做類似的事情。

function find_student() { 
//Generating the array.. 
$array = array("name" => "John", "age" => "23"); 

return new ArrayObject($array); 
} 

echo find_student()->name; 
// Equals to 
$student = find_student(); 
echo $student['name']; 

下降是你不能使用本地陣列功能,如array_merge()對此。但是你可以像訪問數組一樣訪問數據,就像訪問對象一樣。

+0

是的,我想這是這樣做的一種方法。謝謝 – 2012-01-12 09:24:55

+0

另外,如果你想使用數組函數,你可以這樣做:(array)find_student(); – Prof83 2012-11-21 22:54:35