你可以取消注册关机功能吗?

nic*_*ckf 26 php

是否有可能在PHP中取消注册设置的功能(或所有功能)register_shutdown_function()

Tyl*_*ter 23

我不相信你能.取消注册回调函数的唯一方法是将它包装在某种类中,该类仅基于某些条件实际调用它.像这个方便的函数包装器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

基本用法:

$callback = new UnregisterableCallback(array($object, "myFunc"));

register_shutdown_function(array($callback, "call"));
Run Code Online (Sandbox Code Playgroud)

取消注册

$callback->unregister();
Run Code Online (Sandbox Code Playgroud)

现在,当被调用时,它将返回false并且不会调用您的回调函数.可能有几种方法可以简化此过程,但它可以正常工作.

简化它的一种方法是将回调的实际注册放入回调函数的方法中,因此外界不必知道您必须传递给register_shutdown_function的方法是"call".


God*_*You 5

您好,我对函数的工作方式做了一些小小的修改,如下所示:

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;
Run Code Online (Sandbox Code Playgroud)