退出php命令而不触发关机功能

时间:2013-02-19 11:07:55

标签: php callback exit abort atexit

如何退出php脚本(例如使用exit()函数)但不触发所有先前注册的关闭函数(使用register_shutdown_function)?

谢谢!

编辑:或者,有没有办法从所有已注册的关机功能中清除?

2 个答案:

答案 0 :(得分:5)

如果使用SIGTERM或SIGKILL信号终止进程,则不会执行关闭函数。

posix_kill(posix_getpid(), SIGTERM);

答案 1 :(得分:2)

请勿直接使用register_shutdown_function。创建一个管理所有关闭函数的类,它具有自己的函数和启用属性。

class Shutdown {

    private static $instance = false;
    private $functions;
    private $enabled = true;

    private function Shutdown() {
        register_shutdown_function(array($this, 'onShutdown'));
        $this->functions = array();
    }

    public static function instance() {
        if (self::$instance == false) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function onShutdown() {
        if (!$this->enabled) {
            return;
        }

        foreach ($this->functions as $fnc) {
            $fnc();
        }
    }

    public function setEnabled($value) {
        $this->enabled = (bool)$value;
    }

    public function getEnabled() {
        return $this->enabled;
    }

    public function registerFunction(callable $fnc) {
        $this->functions[] = $fnc;
    }

}