I just want to make sure I understand this point. For a while I thought destructors run when the script ends.
On the PHP manual I read “The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.”
The first part, “as soon as there are no other references to a particular object” can you tell me if the below code is accurate? But I’m not sure what the second part means “or in any order during the shutdown sequence”.
// begin script
$instantiate = new Test();
$instantiate->firstMethod();
$instantiate->secondCall();
// no more calls to the $instantiate object so the destructor would run now
// other script processing, but no references to $instantiate
// end script
AFAIK unless you call a
$instantiate->close();
or similar, how would PHP know whether or not there would be more calls to it?
I don’t think it has “look ahead” ability.
So in this case, unless it was passed as an include or a resource it would be when the script ends.
I read that as well, its inaccurate. Destructors are called at the end of execution of the script, unless they are unset. But that’s just how its running now, bottom line, don’t rely on destructors to run when you want them too. If you have something that needs done, set a method to do what you need and call it.
Not Unsetting:
<?php
class destruct {
private $id;
public function __construct($id) {
$this->id = $id;
print "construct " . $this->id . "\
";
}
public function test() {
print "testing " . $this->id . "\
";
}
public function __destruct() {
print "desctruct " . $this->id . "\
";
}
}
$d1 = new destruct(1);
$d2 = new destruct(2);
$d1->test();
print "some procedural stuff\
";
$d2->test();
/*
construct 1
construct 2
testing 1
some procedural stuff
testing 2
desctruct 2
desctruct 1
*/
Unsetting:
<?php
class destruct {
private $id;
public function __construct($id) {
$this->id = $id;
print "construct " . $this->id . "\
";
}
public function test() {
print "testing " . $this->id . "\
";
}
public function __destruct() {
print "desctruct " . $this->id . "\
";
}
}
$d1 = new destruct(1);
$d2 = new destruct(2);
$d1->test();
unset($d1);
print "some procedural stuff\
";
$d2->test();
/*
construct 1
construct 2
testing 1
desctruct 1
some procedural stuff
testing 2
desctruct 2
*/
So, even though you say “don’t rely on destructors to run when you want”, they’ll still always run, correct? I have a database class and my destructor just closes the connection, i figure that’s safe??
I’m saying if you have something critical you want to happen at a certain point, before starting something else, then it doesn’t belong in a destructor. They should be used strictly as cleanup (closing a db connection), and not something like say, updating a record in a db with something (last modified?) after you’ve completed some tasks on it.