There is, but first you have to understand at what moments it runs.
The concept is similar to other languages such as C++, the __destruct
is always triggered when the reference of a "class called" is "destroyed", for example:
$test = new MinhaClasse();
$test = null; //A partir daqui o __destruct provavelmente será chamado (ou no fim do script)
If there is nothing like this in the script and the variable is accessible by other scopes, then the object will stay there until the shutdown
of the script, then the __destruct
will be triggered only when the script has already been completed.
When to use __destruct
Imagine that you have a series of variables in the class or variables of vectors, large and when the class is destroyed you want to clean them, then you can use the __destruct
, this helps in the release of a little memory (it will depend on how the GC behaves, has no way of controlling).
class Foo {
private $bar = array();
public function __construct() {
$this->bar = range(1, 1000000);//Gera um grande vetor
}
public function __destruct() {
$this->bar = null;//libera variável
}
}
You can also use this to disconnect from socket, or mysql without calling mysqli_close
, for example:
class Conexao {
private $link = null;
public function __construct() { //Auto-conecta
$this->link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
}
public function __destruct() {
mysqli_close($this->link);//desconecta
$this->link = null;
}
}
By calling it:
$test = new Conexao();
//...Aqui fica todo o processo que vai usar a conexão
$test = NULL; //A partir daqui provavelmente a classe será destruída
//...Outras tarefas
This way you won’t need to disconnect, the __destruct
will take care of it for you.
About the comment:
.."The destructor has Nothing directly to do with Releasing memory" (...A destructor has nothing to do with releasing memory directly...
He said "immediately", meaning yes, "help" to release, but this does not occur immediately, it is used to release "references" or other tasks, such as disconnecting from a socket
. The release of memory will depend on the GC as I quoted earlier.
The __destruct
does not release the references automatically, it is a method that you should write yourself, in this method you will have to say how and what should be released from the "internal references" of the class, then the references being free the GC will take charge of trying to free the memory.
Thanks. Great example using mysqli_close.
– wdarking