如果你想在 PHP create_function
功能。还Here http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback是有关回调的有趣信息(可能有用)。
使用示例 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);
Returns:
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"
}
Links:
- 回调 http://php.net/manual/en/memcached.callbacks.php
- create_function() http://php.net/manual/en/function.create-function.php
- call_user_func() http://php.net/manual/en/function.call-user-func.php
- is_callable() http://php.net/manual/en/function.is-callable.php