2013-02-26 34 views
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,但是...)。

+0

您推薦的函數返回值取消引用目前在任何版本的PHP中都是不可能的。然而,你可以實現'use'語句來訪問閉包內的'$ someOutsideScopeVar',並將這個功能與'call_user_func'一起使用。 – rdlowrey 2013-02-26 18:18:08

回答

2

在PHP中(> = 5.3.0,使用5.4.6進行測試),您必須使用call_user_func並從外部範圍導入變量use

<?php 

function i_accept_str($str) { 
    // do something with str 
    echo $str; 
} 

$someOutsideScopeVar = array(1,2,3); 
i_accept_str(call_user_func(function() use ($someOutsideScopeVar) { 
    // do stuff with the $someOutsideScopeVar 
    $result = implode(',', $someOutsideScopeVar); // this is silly example 
    return $result; 
}));