News

My campaign to produce Shakespeare's Sonnets: A Graphic Novel Adaptation needs your help! Please sign up at https://www.patreon.com/fisherking for access to exclusive content and the opportunity to be a part of the magic!

I'm also producing a podcast discussing the sonnets, available on
industrial curiosity, itunes, spotify, stitcher, tunein and youtube!
For those who prefer reading to listening, the first 25 sonnets have been compiled into a book that is available now on Amazon and the Google Play store.

Tuesday, 28 July 2015

Write a destructor in PHP for fatal error handling

This just posted on stackoverflow.

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!

No comments:

Post a comment

Priority pinning in apt-preferences with different versions and architectures

I'm posting this because I've lost too many hours figuring it out myself, the documentation is missing several important notes and I...