PHP __Constructor & __Destructor Questions

I was trying to learn the object-oriented side of PHP and was wondering:

If I used _constructor to open a database connection, used a function inside that class (like insert), will the specified __destructor close the connection after the "insert" method is executed?

class data(){
  function __constructor {
    // connect to db
  }

  function insert($data){
    // mysql_query(...)
  }

  function __destructor {
    // close connection to db
  }
}

$obj = new db();
$obj->insert('mumbo jumbo');

      

Or will the database connection be open? The reason I am reading is that the destructor only starts when the object is destroyed. But how do you destroy the object?

+2


source to share


5 answers


In PHP, an object is destroyed when it goes out of scope. This usually happens when the script stops executing or when the function has been created at the end, but you can destroy the object at the beginning of your code using:

unset($my_variable);  

      



So, to answer your question, you should be fine with letting the destructor handle the database shutdown for you in most situations, especially with small scripts.

+6


source


Yes, it will work fine if you use the correct names, __construct()

and__destruct()

, for your constructors and destructors, as opposed to what you have.



+3


source


The object is destroyed if there is no longer a reference to it, such as the unset()

-ting of the last variable holding the object, or when the script finishes executing.

Incidentally, the magic methods are called __construct

, and __destruct

without end -or

.

+2


source


BTW, constructors and destructors are called __construct and __destruct.

__ destructor will be called when there are no more references to db

. Typically this happens when the object goes out of scope, but if you've saved other references to it, it won't. You can remove links to db

using

unset($obj);

      

and similarly if you saved $ obj anywhere.

+1


source


Keep in mind that PHP also supports persistent database connections, which means that even if your object was destroyed, the database connection is still open "in the background" and will be reused when you call the appropriate pconnect (or PDO ) next.

0


source







All Articles