usoban
usoban

Reputation: 5478

Call function when script is terminated

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?

Upvotes: 7

Views: 4589

Answers (3)

CoDeR
CoDeR

Reputation: 53

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().

Upvotes: 0

simonrjones
simonrjones

Reputation: 1182

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!

Upvotes: 4

Scharrels
Scharrels

Reputation: 3055

use register_shutdown_function():

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

Upvotes: 17

Related Questions