Szymon Toda Szymon Toda - 5 months ago 15
PHP Question

Can PHP object can destruct itself on construct?

Can

function __construct()
destruct itself after construction?

Like in following pseudo-code, and if yes than how to do it:

function __construct() {
if($something) echo "OK!"
else __destruct();


}

Answer

Method __destruct is a magic method in PHP and must not be called manually.

Hovewer it does not do any real magic, the name of the method should be something like onDestructed or so, just like an event listener.

So, __destruct is called when there are no more references to the object. The implementation of method could be the following:

function __destruct(){
  echo "An object of class " . __CLASS__ . " has been destroyed " ;
}

And to answer your question, yes, it can be called explicitly, and you will just execute the code inside method __destruct, but you will not destroy the object (unless you do some real garbage collection inside it).

function __construct($something) {
  if($something) 
    echo "OK!" ;
  else 
    $this->__destruct(); // $this-> must be used here!
}

To destroy it, you can use unset($object) or just set it to null in some cases.