Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __Constructor & __Destructor Questions

I've been trying to learn the object oriented side of PHP, and was wondering:

If I used a _constructor to open a connection to a database, used a function within that class (eg. insert), would the defined __destructor close the connection after the method "insert" 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 would the connection to the database still be open? Cause I read that the destructor is only run if the object is destroyed. But how do you destroy an object?

like image 701
chutsu Avatar asked Aug 08 '26 20:08

chutsu


2 Answers

In PHP, an object is destroyed when it goes out of scope. This is normally when the script stops executing or when the function it was created within ends, but you can destroy an object early in your code using:

unset($my_variable);  

So, to answer your question, you should be fine allowing the destructor to handle closing the DB for you in most situations, especially with small scripts.

like image 58
Mark Avatar answered Aug 10 '26 09:08

Mark


Yes, that will work fine, as long as you use the correct names, __construct() and __destruct(), for your constructors and destructors, as opposed to what you have there.

like image 41
chaos Avatar answered Aug 10 '26 08:08

chaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!