Moak
Moak

Reputation: 12865

Call an object method when a PHP script is done

If I have instantiated an object, is there a possible way for it to trigger a method before php shutsdown? example

class foo{
   public function sayBye(){
       echo 'bye';
   }
}
$obj = new foo();
$obj2 = new foo();
die();

Is there a way I could automatically trigger the sayBye function? (in otherwords that code would output "byebye")

Upvotes: 1

Views: 110

Answers (4)

nyson
nyson

Reputation: 1055

The most easy way I can see is that you add a destructor to your class.

class foo{
   public function sayBye(){
       echo 'bye';
   }

   public function __destruct(){
       $this->sayBye();
   }
}

What will this do? When script execution is done or unset($object) is called, you will execute the code within __destruct(). It will probably not work with die(), as this will stop the script hastily before the script is done.

Upvotes: 0

Berry Langerak
Berry Langerak

Reputation: 18859

If I have instantiated an object, is there a possible way for it to trigger a method before php shutsdown? example

There is. Check out __destruct() for more on that. Do note, however, that this is not reliable: if your script contains die(), an uncaught exception, a fatal error, the __destruct() will not be called.

You can use it, but use it wisely ;)

EDIT: it appears the __destruct( ) will be called when you call exit;. Nonetheless, the warning still goes for the other situations.

Upvotes: 1

Emil Vikström
Emil Vikström

Reputation: 91902

Check out the register_shutdown_function function.

Upvotes: 4

Scott C Wilson
Scott C Wilson

Reputation: 20016

What about putting a call to sayBye() in the destructor?

http://php.net/manual/en/language.oop5.decon.php

Upvotes: 2

Related Questions