在 PHP 中通过引用传递函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6475136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a function by reference in PHP
提问by Pwnna
Is it possible to pass functions by reference?
是否可以通过引用传递函数?
Something like this:
像这样的东西:
function call($func){
$func();
}
function test(){
echo "hello world!";
}
call(test);
I know that you could do 'test'
, but I don't really want that, as I need to pass the function by reference.
我知道你可以这样做'test'
,但我真的不想要那样,因为我需要通过引用传递函数。
Is the only way to do so via anonymous functions?
是通过匿名函数这样做的唯一方法吗?
Clarification: If you recall from C++, you could pass a function via pointers:
说明:如果你回忆一下 C++,你可以通过指针传递一个函数:
void call(void (*func)(void)){
func();
}
Or in Python:
或者在 Python 中:
def call(func):
func()
That's what i'm trying to accomplish.
这就是我正在努力实现的目标。
回答by
For what it's worth, how about giving something like this a shot? (Yes, I know it's an anonymous functionwhich was mentioned in the post, but I was disgruntled at the abundance of replies that did not mention closures/function-objects at allso this is mostly a note for people running across this post.)
对于它的价值,试一试这样的东西怎么样?(是的,我知道这是一个在帖子中提到的匿名函数,但我对大量的回复感到不满,这些回复根本没有提到闭包/函数对象,所以这主要是给浏览这篇文章的人的一个说明。)
I don't use PHP, but using a closureappears to work in PHP 5.3(but not PHP 5.2) as demonstrated here. I am not sure what the limitations, if any, there are.(For all I know the closure will eat your children. You have been warned.)
我不使用 PHP,但使用闭包似乎可以在PHP 5.3(但不是 PHP 5.2)中使用,如此处所示。我不确定有什么限制,如果有的话。(据我所知,关闭会吃掉你的孩子。你已经被警告过。)
function doIt ($fn) {
echo "doIt\n";
return $fn();
}
function doMe () {
echo "doMe\n";
}
// I am using a closure here.
// There may be a more clever way to "get the function-object" representing a given
// named function, but I do not know what it is. Again, I *don't use PHP* :-)
echo doIt(function () { doMe(); });
Happy coding.
快乐编码。
回答by ma?ek
The problem with call_user_func()
is that you're passing the return value of the function called, not the function itself.
问题call_user_func()
在于您传递的是被调用函数的返回值,而不是函数本身。
I've run into this problem before too and here's the solution I came up with.
我以前也遇到过这个问题,这是我想出的解决方案。
function funcRef($func){
return create_function('', "return call_user_func_array('{$func}', func_get_args());");
}
function foo($a, $b, $c){
return sprintf("A:%s B:%s C:%s", $a, $b, $c);
}
$b = funcRef("foo");
echo $b("hello", "world", 123);
//=> A:hello B:world C:123
回答by dhbmarcos
function func1(){
echo 'echo1 ';
return 'return1';
}
function func2($func){
echo 'echo2 ' . $func();
}
func2('func1');
Result:
结果:
echo1 echo2 return1
回答by deceze
No, functions are not first class values in PHP, they cannot be passed by their name literal(which is what you're asking for). Even anonymous functions or functions created via create_function
are passed by an object or string reference.
不,函数不是 PHP 中的一等值,它们不能通过它们的名称文字传递(这就是你所要求的)。甚至匿名函数或通过创建的函数create_function
也由对象或字符串引用传递。
You can pass a name of a function as string, the name of an object method as (object, string)
array or an anonymous function as object. None of these pass pointers or references, they just pass on the name of the function. All of these methods are known as the callback
pseudo-type: http://php.net/callback
您可以将函数的名称作为字符串传递,将对象方法的名称作为(object, string)
数组传递或将匿名函数作为对象传递。这些都没有传递指针或引用,它们只是传递函数的名称。所有这些方法都被称为callback
伪类型:http: //php.net/callback
回答by Pristine Kallio
A similar pattern of this Javascript first class function:
这个 Javascript 第一类函数的类似模式:
function add(first, second, callback){
console.log(first+second);
if (callback) callback();
}
function logDone(){
console.log('done');
}
function logDoneAgain(){
console.log('done Again');
}
add(2,3, logDone);
add(3,5, logDoneAgain);
Can be done in PHP (Tested with 5.5.9-1ubuntu on C9 IDE) in the following way:
可以通过以下方式在 PHP 中完成(在 C9 IDE 上使用 5.5.9-1ubuntu 测试):
// first class function
$add = function($first, $second, $callback) {
echo "\n\n". $first+$second . "\n\n";
if ($callback) $callback();
};
function logDone(){
echo "\n\n done \n\n";
}
call_user_func_array($add, array(2, 3, logDone));
call_user_func_array($add, array(3, 6, function(){
echo "\n\n done executing an anonymous function!";
}));
Result: 5 done 9 done executing an anonymous function!
结果:5 完成 9 完成执行匿名函数!
Reference: https://github.com/zenithtekla/unitycloud/commit/873659c46c10c1fe5312f5cde55490490191e168
参考:https: //github.com/zenithtekla/unitycloud/commit/873659c46c10c1fe5312f5cde55490490191e168
回答by zeroimpl
You can create a reference by assigning the function to a local variable when you declare it:
您可以通过在声明时将函数分配给局部变量来创建引用:
$test = function() {
echo "hello world!";
};
function call($func){
$func();
}
call($test);
回答by Rob Evans
In PHP 5.4.4 (haven't tested lower or other versions), you can do exactly as you suggested.
在 PHP 5.4.4(未测试过更低版本或其他版本)中,您可以完全按照您的建议进行操作。
Take this as an example:
以此为例:
function test ($func) {
$func('moo');
}
function aFunctionToPass ($str) {
echo $str;
}
test('aFunctionToPass');
The script will echo "moo" as if you called "aFunctionToPass" directly.
该脚本将回显“moo”,就像您直接调用“aFunctionToPass”一样。
回答by Scott C Wilson
You can say
你可以说
$fun = 'test';
call($fun);
回答by Brian Graham
Instead of call(test);
, use call_user_func('test');
.
而不是call(test);
,使用call_user_func('test');
。