Created
August 24, 2011 13:16
-
-
Save assertchris/1168029 to your computer and use it in GitHub Desktop.
PHP Events callback methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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