Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something like a callback delegate function in php

Tags:

oop

php

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?

like image 357
George Mauer Avatar asked Sep 07 '08 16:09

George Mauer


People also ask

Does PHP have callback?

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.

What is a callable in PHP?

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.

What is callback method in PHP?

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.

What is delegate PHP?

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.


1 Answers

(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') );
?>
like image 62
VolkerK Avatar answered Oct 01 '22 02:10

VolkerK