1
是否有可能做這樣的事情。比方說,我們有一個接受字符串作爲參數的函數。但是爲了提供這個字符串,我們必須對數據進行一些處理。所以我決定使用閉包,就像在JS:PHP:直接使用匿名函數的結果作爲字符串?
function i_accept_str($str) {
// do something with str
}
$someOutsideScopeVar = array(1,2,3);
i_accept_str((function() {
// do stuff with the $someOutsideScopeVar
$result = implode(',', $someOutsideScopeVar); // this is silly example
return $result;
})());
的想法是調用i_accept_str()
時,能夠直接爲它供給字符串結果......我大概可以用call_user_func
這是衆所周知的是做無效但有其他選擇嗎?
接受PHP 5.3和PHP 5.4解決方案(以上想要的行爲已經過測試,並且不適用於PHP 5.3,但可能適用於PHP 5.4,但是...)。
您推薦的函數返回值取消引用目前在任何版本的PHP中都是不可能的。然而,你可以實現'use'語句來訪問閉包內的'$ someOutsideScopeVar',並將這個功能與'call_user_func'一起使用。 – rdlowrey 2013-02-26 18:18:08