Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

register_shutdown_function() and die()

Tags:

php

die

smarty

Can I somehow check, if my script was canceled by die() in register_shutdown_function()?

Something like this:

register_shutdown_function('shutdown');

die('Calling die()');

function shutdown()
{
    if (???)
    {
        // Script was canceled by die()
    }
}

NOTE: On my website, I use Smarty. So maybe check, if $smarty->display() was called or something like that?

like image 839
Koralek M. Avatar asked May 14 '12 15:05

Koralek M.


1 Answers

Kind of... but you won't necessarily like how it has to be done.

Since there is no hook that allows you to check if die was called, you will have to somehow fake it. Assuming that you cannot touch all calls to die, that leaves only one option: set some state that signifies "die was called" by default, and remove that state only at the very end of your script, when you know that you are going to exit without die having been called earlier.

"Set some state" sounds suspiciously like global variables and that should be a last resort, so let's use a constant for state:

register_shutdown_function('shutdown');
if (condition) die('Calling die()');

// since we reached this point, die was not called
define('DIE_NOT_CALLED', true);

function shutdown()
{
    if (!defined('DIE_NOT_CALLED'))
    {
        // Script was canceled by die()
    }
}

See it in action.

like image 94
Jon Avatar answered Oct 23 '22 04:10

Jon