Connections and management

Asked

Viewed 100 times

2

PHP - PDO, Connections and Connection Management

The connection remains active throughout the lifetime of the PDO object. To close the connection, you need to destroy the object, ensuring that all remaining references to it are deleted - you do this by assigning NULL to the variable containing the object. If you don’t do this explicitly, PHP will automatically close the connection when the script ends.


By PDO manual, simply assign NULL.

$database = new PDO( ... ) // instância
$database = null           // close

My doubt came when I read the singular: a variável que contém o objeto.
See the example below.

The PDO instance is present in $pdo and Crud $pdo.
In cases like this, where the object is in two variables, both must be NULL?

$pdo = new PDO( ... )

class Crud
{
     function insert( $pdo, $argumentos )
     {
          $this-> pdo = $pdo;
     }
}


OBS
1) I know it is optional because PHP does it at the end as shown in the DOC
2) It is a simple and illustrative example, any question about PATTERN should be ignored :)

1 answer

5


Yes, if more than one variable points to the same object, they all need to receive null so that the memory occupied by the object is released.

PHP maintains a reference count for the objects. When the Garbage Collector wheel, it searches for objects with zero references, and releases the corresponding memory. If there is one or more references to a particular object, it is considered "alive" (in use), and therefore the memory it occupies cannot be released.

Since PDO type objects do not have a method to close the connection, it is only closed when the object is effectively destroyed, so the procedure described above is necessary.

  • I will read the reference link. thanks for the explanation, I did not know this PHP procedure to clear the memory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.