hanut
hanut

Reputation: 515

Scope of PDO used in a function

I am using a structure like the one below -

class foo{
.
.
.

  function bar($colID){
     try{
        $dbo = new PDO(get_db_DSN(), 
                       get_db_USR(), 
                       get_db_PWD());
        $pstmt = $dbo->prepare("SELECT * FROM table_name WHERE col=:colID");
        $pstmt->bindValue(':colID', $colID);
        $pstmt->execute();
        .
        .
        .
     }catch(PDOException e){
      ...
      }
}

I need to know if the PDO will persist till the object of foo exists or if it will be destroyed right after the end of the function's scope.

Upvotes: 0

Views: 73

Answers (2)

sectus
sectus

Reputation: 15454

After bar $dbo will be "destroyed".

Variable containers get destroyed when the "refcount" reaches zero. The "refcount" gets decreased by one when any symbol linked to the variable container leaves the scope (e.g. when the function ends) or when unset() is called on a symbol.

Reference Counting Basics

Upvotes: 2

jtavares
jtavares

Reputation: 449

it will be garbage collected... if you want it to be available after the function returns you should use a foo property to store it.

class foo{
.
.
.

var $dbo;  

  function bar($colID){
     try{
        $this->dbo = new PDO(get_db_DSN(), get_db_USR() get_db_PWD());

        .
        .
        .
     }catch(PDOException e){
      ...
      }
}

Upvotes: 0

Related Questions