PHP: destructor vs register_shutdown_function

后端 未结 4 1937
不思量自难忘°
不思量自难忘° 2020-12-16 01:19

I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that imagedestroy function is called at end

4条回答
  •  青春惊慌失措
    2020-12-16 01:42

    I recently had trouble with this as I was trying to handle destruction specifically for the case where the server experiences a timeout and I wanted to include class data in the error log. I would receive an error when referencing &$this (although I've seen it done in a few examples, possibly a version issue or a symfony side-effect), and the solution I came up with was fairly clean:

    class MyClass
    {
        protected $myVar;
    
        /**
         * constructor, registers shutdown handling
         */
        public function __construct()
        {
            $this->myVar = array();
    
            // workaround: set $self because $this fails
            $self = $this;
            // register for error logging in case of timeout
            $shutdown = function () use (&$self) {
                $self->shutdown();
            };
            register_shutdown_function($shutdown);
        }
    
        /**
         * handle shutdown events
         */
        public function shutdown()
        {
            $error = error_get_last();
            // if shutdown in error
            if ($error['type'] === E_ERROR) {
                // write contents to error log
                error_log('MyClass->myVar on shutdown' . json_encode($this->myVar), 0);
            }
        }
    
        ...
    

    Hope this helps someone!

提交回复
热议问题