Connections and management

2

PHP - PDO, Connections and connection management

  

The connection remains active for the entire life of the PDO object. To close the connection, you must destroy the object, ensuring that all the references remaining to it are deleted - you do this by assigning NULL to the variable containing the object . If you do not explicitly do this, PHP will automatically close the connection when the script ends.


From the PDO manual, just assign NULL.

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

My question came up 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 should be NULL?

$pdo = new PDO( ... )

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


  I know it's optional because PHP does this in the end as it shows DOC
2) It's a simple example and illustrative, any question about PATTERN should be ignored:)

    
asked by anonymous 30.08.2014 / 07:29

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 freed.

PHP maintains a reference count for objects. When the garbage collector runs, it looks for objects with zero references, and releases the corresponding memory. If there are one or more references to a given object, it is considered "alive" (in use), and therefore the memory it occupies can not be released.

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

    
30.08.2014 / 14:22