我想做这样的事情:
function func($callback) {
$result = $callback(???); // $callback must be called here
//...
}
//...
func(function(['foo' => 'buu']) {
$a = func_get_arg(0);
// do something with $a and return something...
return $something;
})
可以在php中使用吗?
我可以做下面的事情,但这不是我想要做的:
function func($args, $callback) {
$result = $callback($args);
//...
}
func(['foo' => 'boo'], function($args) {
$a = $args; // etc.
})
答案 0 :(得分:3)
我通过这种方式使用匿名函数:
$mySuperFunction = function($arg)
{
echo ("Hello " . $arg);
};
function AnotherFunction($args)
{
echo ("Another hello " . $args);
}
function WrappingAnonymous($callback, $args)
{
$callback($args);
}
function WrappingAnonymousWithoutArgs($callback)
{
$callback();
}
WrappingAnonymous($mySuperFunction, "World");
WrappingAnonymous("AnotherFunction", "World");
WrappingAnonymous(function($someArgs)
{
echo "Yet another Hello " . $someArgs;
}, "World");
WrappingAnonymousWithoutArgs(function($someArgs = "World")
{
echo "Now, a 4th other Hello " . $someArgs;
});
输出:
Hello World
另一个你好世界
又一个Hello World
现在,第四个Hello World