Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created August 24, 2011 13:16
Show Gist options
  • Save assertchris/1168029 to your computer and use it in GitHub Desktop.
Save assertchris/1168029 to your computer and use it in GitHub Desktop.
PHP Events callback methods
$callbacks = null;
function addEvent($type, $callback)
{
global $callbacks;
if (empty($callbacks))
{
$callbacks = array();
}
if (empty($callbacks[$type]))
{
$callbacks[$type] = array();
}
$callbacks[$type][] = $callback;
}
function fireEvent($type)
{
global $callbacks;
if (!empty($callbacks[$type]))
{
foreach ($callbacks[$type] as $callback)
{
call_user_func($callback);
}
}
}
function removeEvent($type, $callback)
{
global $callbacks;
if (!empty($callbacks[$type]))
{
foreach ($callbacks[$type] as $i => $found)
{
if ($callback == $found)
{
unset($callbacks[$type][$i]);
break;
}
}
}
}
$callback = function(){
echo 'hello!';
};
addEvent('speak', $callback);
fireEvent('speak');
removeEvent('speak', $callback);
fireEvent('speak');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment