问题描述
我想实现类似于PHP中的c#委托方法的东西.一个简短的词可以解释我总体上想做的事情:我正在尝试实现一些异步功能.基本上,一些资源密集型调用在底层系统运行时会排队,缓存和调度.当异步调用最终收到响应时,我希望引发一个回调事件.
I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.
我在用PHP进行回调的机制上遇到了一些问题.我想出了一种目前可以使用的方法,但对此我感到不满意.基本上,它涉及传递对对象的引用以及对象上的方法名称,该对象将用作回调(将响应作为参数),然后在需要时使用eval调用该方法.由于种种原因,这是次优的选择,有没有人知道的更好的方法呢?
I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?
推荐答案
(除了观察者模式之外),您还可以使用 call_user_func()
或 call_user_func_array()
.
(Apart from the observer pattern) you can also use call_user_func()
or call_user_func_array()
.
如果将array(obj, methodname)
作为第一个参数传递,它将作为$obj->methodname()
调用.
If you pass an array(obj, methodname)
as first parameter it will invoked as $obj->methodname()
.
<?php
class Foo {
public function bar($x) {
echo $x;
}
}
function xyz($cb) {
$value = rand(1,100);
call_user_func($cb, $value);
}
$foo = new Foo;
xyz( array($foo, 'bar') );
?>
这篇关于类似于php中的回调委托函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!