2012-09-06 41 views
3

我有一個類似的代碼:使用閉包

$name = '_DBR'; // This comes from a function call 

$this->_Inits['_DBR'] = function() { return get_library('Database')->getConnection('users', 'read'); }; 

$inits = $this->_Inits[$name]; 
$result = $inits(); // ERROR: Function name must be a string 

return $result; 

我得到的錯誤是:

Function name must be a string in xxxx 

有什麼辦法,我可以使用一個數組存儲多個封閉和有沒有一種工作方式來訪問它們?

我使用PHP 5.4.3

+1

對於我來說,通過引用調用函數似乎有點奇怪。在測試時,我有這樣的警告:'嚴格的標準:只有變量應該通過引用分配' – Tchoupi

+0

是的,我刪除了引用的返回,編輯帖子。 – Manhim

回答

3

這對我在php 5.3.10中正常工作。

$m = array(); 
$m['fish'] = function() { print "Hello\n"; }; 
$f = $m['fish']; 
$f(); 
+0

哇,在我犯了錯誤的實際代碼中,這就是爲什麼它不起作用。感謝你的回答! – Manhim

3

是的,改用call_user_func。