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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With