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.
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?
Callbacks can be denoted by the callable type declaration. Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.
The callable keyword is used to force a function argument to be a reference to a function. A callable can be one of the following: An anonymous function. A string containing the name of a function. An array describing a static class method.
A callback function (often referred to as just "callback") is a function which is passed as an argument into another function. Any existing function can be used as a callback function.
This is delegation – a process by which one object implements a particular behavior by sending messages to another object which implements the same or a similar behavior. You are going to modify the DBQuery object to include all functions which work on a result resource from the DB object.
(Apart from the observer pattern) you can also use call_user_func()
or call_user_func_array()
.
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') );
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With