tags:

views:

71

answers:

3

Hello

I'd like to call a function when the script is terminated by die() or exit(). My wish is to do this automatically, so I don't have to call function all the time.

Is this possible?

+5  A: 

use register_shutdown_function():

http://docs.php.net/manual/en/function.register-shutdown-function.php

Scharrels
Thank you, haven't found anything on google and I didn't think there actually is a function ;)
usoban
the exit() function in the php documentation links to it. The PHP documentation is regularly the best start to look for this kind of questions.
Scharrels
A: 

I don't know if this helps, but you can do it the other way around

define a function like this

function terminate() // you might want to have parameters here to handle different cases { the_Function_to_Call(); die(); // or exit();

}

then inside your code call terminate() instead of die() or exit()

CoDeR
+2  A: 

The __destruct() magic method for classes also runs at shutdown, unless you unset the class object first. Though Scharrels response is simpler if you just want to register a normal function. See http://docs.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.destructor

One thing to bear in mind when running scripts in shutdown is this happens after the output is sent to the browser, so you won't get any errors displayed to screen. Make sure you remember to log errors to file for shutdown functions!

simonrjones
I know about __destruct() for destroying objects, but this doesn't help me. I have a class for session manipulation. The reason I don't want to use __destruct() on the object is, because I want to properly save session data right at the end, and session object can be destroyed during script processing. Thanks anyway ;)
usoban
If this is for session data management you should look at session_set_save_handler() - this has its own system, a write handler, to save session data in shutdown without the need for registering shutdown functions yourself. See http://php.net/manual/en/function.session-set-save-handler.php
simonrjones