Electricmonk

Ferry Boender

Programmer, DevOpper, Open Source enthusiast.

Blog

Callback functions in PHP

Wednesday, September 26th, 2007

I was implementing a plugin system for a framework I’m writing, and I needed plugins to be able to register a callback function or method with the Plugin Manager so that the callback function would get called when a signal was emitted. Here’s a very stripped down version of what I ended up with:

callback_method()\n");
	}

	// Sample static callback method
	public static function callback_method_static() {
		print("Callback::callback_method_static()\n");
	}
}

// Hook class with which you register callback functions and methods
// which will be called when you call the emit() method.
class Hook
{
	private $callbacks = array(); // All the registered callbacks.

	//
	// Register a function/method as a callback function.
	//
	public function registerCallback($callback) {
		$this->callbacks[] = $callback;
	}

	//
	// Run all the functions/methods registered as callbacks.
	//
	public function emit() {
		foreach($this->callbacks as $callback) {
			call_user_func($callback);
		}
	}
}

// Create a hook class instance with which we will register our
// callbacks.
$hook = new Hook();

// Instantiate the sample callback class.
$callback = new Callback();

// Register all the sample callbacks with the Hook class instance.
$hook->registerCallback('callback_function');
$hook->registerCallback(array($callback, 'callback_method'));
$hook->registerCallback(array('Callback', 'callback_method_static'));

// Make the Hook class instance call all the registered callback
// methods.
$hook->emit();

?>

First, we set up some sample callback functions and methods (callback_function(), Callback->callback_method() and Callback::callback_method_static()). Then we define the Hook class with which we can register callback functions. Finally, we register our sample callbacks with the Hook class and emit the ‘signal’.

Right now, there’s only a single signal (or no signal at all, depending on how you look at it), but that’s easy to implement. The magic basically is in the emit() method of the Hook class. It iterates over the registered callbacks, which is nothing more than an array containing either strings for function callbacks or arrays for static and non-static callback methods. It then calls those using the call_user_func() method.

All this results in the following output, when ran:

callback_function()
Callback->callback_method()
Callback::callback_method_static()

Nothing fancy, and I must have implemented something similar a gazillion times, but I thought I’d share it with you all.

The text of all posts on this blog, unless specificly mentioned otherwise, are licensed under this license.