如果你想在 PHP create_function 函数。 Here 也是关于回调的有趣信息(可能有用)。
使用示例 create_function
# This (function in other variable is only for cleaner code)
$func = create_function('', "echo 'This is example from anoymus function';");
$exampleArray = array(
'func' => $func
);
但是您可以通过其他方式对上面的代码执行相同的操作:
# Create some function
function func()
{
# Do something
echo 'This is example';
}
# Save function name
$func = 'func';
上面的代码创建了函数,然后我们将函数名存储在变量中(可以作为参数传递等)。
当我们只知道它的名字时调用函数:
第一种方式
$func();
替代方案
call_user_func($func);
连接以上所有内容的示例:
function primitiveArrayStep(&$array, $function)
{
# For loop, foreach can also be used here
for($i = 0; $i < count($array);$i++)
{
# Check if $function is callable
if( is_callable($function) )
{
# Call function
$function(&$array[$i]);
}
else
{
# If not, do something here
}
}
}
以及上述功能的使用:
$array = array('a', 'b', 'c');
$myFunction = create_function('&$e', '$e = $e . " and i was here";');
primitiveArrayStep($array, $myFunction);
echo '<pre>';
var_dump($array);
返回:
array(3) {
[0]=>
string(16) "a and i was here"
[1]=>
string(16) "b and i was here"
[2]=>
string(16) "c and i was here"
}
链接: