In PHP, there is no Garbage Collector, but destructor methods
I think you're wrong. PHP: Garbage Collection
Where and when to use the destructor method?
The concept of destruct is equal to the C ++ language:
The destructor method will be called as soon as there are other references to a particular object , or in any order during the shutdown sequence.
You do not directly use the __destruct
method, but PHP will use it automatically as soon as there is no further reference to the object.
You can use the __destruct
method when there is a need to perform some operation (automatically) only when the object will no longer be used. For example, releasing some resource or releasing objects that are associated with your object.
The most common example is with database connections:
class Connection {
private $pdo;
public function __construct() {
$this->pdo = new PDO(/** connection data **/);
}
public function __destruct() {
//PDO se desconecta automaticamente quando não houver mais referências ao objeto
//Ou seja, internamente utiliza o método __destruct
$this->pdo = null;
}
}
You can interpret that PDO also uses the __destruct
method, because, since there are no more references to the object, the connection to the database
will be closed.
The link below may give you some idea of how the garbage collector works and the PHP references:
Does the destructor method run automatically when the page is closed?
The method runs whenever the object no longer has any references or PHP script finishes its execution. That is, when your site finished loading completely, the __destruct
method has already been executed by PHP. The methods will be executed even if the script is stopped using the exit
/ die
functions. They will not be executed by any execution failure or if the exit
/ die
function is called within a __destruct
method.
The destructor will be called even if script execution is stopped using exit (). Calling exit () in a destructor will prevent the remaining shutdown routines from executing.
Unlike Java and .NET, where there is an application running on a server, PHP does not have an application that is always running. The PHP application is created the moment a request is received. The application executes all its script (according to the request) and then, after all execution and output, the application is destroyed. Therefore, the __destruct
method will always be executed.
If I give F5 on the page, will the old object be replaced with a new one or will both be kept in memory?
As explained in the application, your objects will always be destroyed and new objects will be created. This is a peculiarity of the PHP architecture.
link