Rik de Vos Rik de Vos - 3 months ago 27
PHP Question

Enqueue a function (like wordpress add_action)

How do I queue functions in PHP? I need something that works just like Wordpress's

system. I want enqueue function which then runs when the time is right.


This seems to work perfectly. Anyone got any tips to improve my code?

$enqueued_actions = array();

* Enqueue an action to run at a later time.
* @param string $hook The hook name.
* @param obj $func The function object.
* @param integer $imp The level of importance from 0-9
function add_action($hook, $func, $imp = 0) {

global $enqueued_actions;

$enqueued_actions[$hook][] = array('func' => $func, 'imp' => $imp);

* Run the enqueued actions with the correct hook.
* @param string $hook Hook name.
function run_action($hook) {

global $enqueued_actions;

$actions = $enqueued_actions[$hook];

for($i = 0; $i < 9; $i++) {
foreach($enqueued_actions[$hook] as $action) {
if($action['imp'] == $i) {



You are on the right track here. You might want to make the hooks persistent, though, i.e. saving the hooks into a database, a CSV file, an XML object model, etc.

Also, you might want to introduce a function for the sake of calling all the actions that have been latched to a certain hook, something like call_actions($hook);