在PHP中通过引用传递函数 [英] Pass a function by reference in PHP
问题描述
是否可以通过引用传递函数?
Is it possible to pass functions by reference?
类似这样的东西:
function call($func){
$func();
}
function test(){
echo "hello world!";
}
call(test);
我知道您可以执行'test'
,但是我真的不想要那样,因为我需要通过引用传递函数.
I know that you could do 'test'
, but I don't really want that, as I need to pass the function by reference.
通过匿名函数这样做是唯一的方法吗?
Is the only way to do so via anonymous functions?
说明:如果您从C ++调用,可以通过指针传递一个函数:
Clarification: If you recall from C++, you could pass a function via pointers:
void call(void (*func)(void)){
func();
}
或者在Python中:
Or in Python:
def call(func):
func()
这就是我要完成的工作.
That's what i'm trying to accomplish.
推荐答案
对于它的价值,给这样的镜头打些怎么样? (是的,我知道这是一个匿名函数,在帖子中提到了,但是我对大量的答复没有提及闭包/函数感到不满,根本没有对象,所以这主要是为这篇文章中奔跑的人们提供的注释.)
For what it's worth, how about giving something like this a shot? (Yes, I know it's an anonymous function which was mentioned in the post, but I was disgruntled at the abundance of replies that did not mention closures/function-objects at all so this is mostly a note for people running across this post.)
我不使用PHP ,但是 使用闭包 在 PHP 5.3 (但不是PHP 5.2)中似乎可以作为此处演示. 我不确定有什么限制(如果有的话).(据我所知,关闭会吞噬您的孩子.您已被警告.)
I don't use PHP, but using a closure appears 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.)
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(); });
快乐的编码.
这篇关于在PHP中通过引用传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!