Can you unregister a shutdown function?

后端 未结 2 1716
遇见更好的自我
遇见更好的自我 2020-12-24 02:17

Is it possible in PHP to unregister a function (or all functions) set up with register_shutdown_function()?

相关标签:
2条回答
  • 2020-12-24 02:40

    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".

    0 讨论(0)
  • 2020-12-24 02:44

    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;
    
    0 讨论(0)
提交回复
热议问题