Is it possible in PHP to unregister a function (or all functions) set开发者_如何学Go up with register_shutdown_function()
?
I do not believe you can. The only way to unregister a callback function is to wrap it in some sort of class that only actually calls it based on certain conditions. Like this handy function wrapper:
class UnregisterableCallback{
// Store the Callback for Later
private $callback;
// Check if the argument is callable, if so store it
public function __construct($callback)
{
if(is_callable($callback))
{
$this->callback = $callback;
}
else
{
throw new InvalidArgumentException("Not a Callback");
}
}
// Check if the argument has been unregistered, if not call it
public function call()
{
if($this->callback == false)
return false;
$callback = $this->callback;
$callback(); // weird PHP bug
}
// Unregister the callback
public function unregister()
{
$this->callback = false;
}
}
Basic usage:
$callback = new UnregisterableCallback(array($object, "myFunc"));
register_shutdown_function(array($callback, "call"));
To unregister
$callback->unregister();
Now, when called, it will return false and not call your callback function. There might be a few ways to streamline this process, but it works.
One such way of streamlining it would be to put the actual registration of the callback into a method of the callback function, so the outside world does not have to have knowledge that the method you have to pass to register_shutdown_function is "call".
Hi I made a slight modification to the way my function worked as follows:
function onDie(){
global $global_shutdown;
if($global_shutdown){
//do shut down
}
}
$global_shutdown = true;
register_shutdown_function('onDie');
//do code stuff until function no longer needed.
$global_shutdown = false;
精彩评论