2013-07-06 46 views
9

爲了從函數返回PHP中一個必備的參考:在 兩個函數聲明是否有可能從PHP中的閉包返回一個引用?

...使用引用操作符&和指派返回值 變量時。

這最終看起來像:

function &func() { return $ref; } 
$reference = &func(); 

我試圖返回從封閉的參考。在一個簡單的例子中,我想要達到的是:

$data['something interesting'] = 'Old value'; 

$lookup_value = function($search_for) use (&$data) { 
    return $data[$search_for]; 
} 

$my_value = $lookup_value('something interesting'); 
$my_value = 'New Value'; 

assert($data['something interesting'] === 'New Value'); 

我似乎無法得到從函數返回引用的常規語法工作。

回答

11

您的代碼應該是這樣的:

$data['something interesting'] = 'Old value'; 

$lookup_value = function & ($search_for) use (&$data) { 
    return $data[$search_for]; 
}; 

$my_value = &$lookup_value('something interesting'); 
$my_value = 'New Value'; 

assert($data['something interesting'] === 'New Value'); 

檢查this出來:

+0

明白了一個。要記住另一個sytax的奇怪選擇。謝謝! – Sam152

相關問題