Home > Article > Backend Development > PHP destructor problem?
Ask me about php destructor
<?php class a{ static $ss=null; function ff($p){ self::$ss=$p; return self::$ss; } function destruct(){ echo "一二三"; } } $rrrr=new a(); echo $rrrr->ff(4444); $aaaa=new a(); echo $aaaa->ff(55555);
========================
Output result: 444455555 one two three one two three
======================
What I want to ask is, destruction Isn't the function executed after object is destroyed? When object $rrrr is executed, the object $rrrr should have been destroyed when $aaaa is executed. After this destruction, the destructor's "one, two, three" should be output. "But the result we see is, 444455555 one two three one two three. I think the result should be 4444 one two three 55555 one two three. This is correct.
It's not like this. unset($rrrr) may trigger object destruction, but new a() will not. You just obtained two instances of a and did not perform destruction.
After the page access is completed, PHP automatically destructs the instances $rrrr and $aaaa, so one, two, and three are output twice in a row.
Thank you, but this is single case mode
static $ssWhen this class variable is reassigned, won’t the previous one be destroyed?
Dear , yours is not a singleton mode...it is just an ordinary object with staticproperties, and even if it is a singleton mode, it will not use destructor. You have to be very careful when learning the program, details are so important. This is a single item
class singleDemo { protected static $instance = false; protected construct() { } public static function getInstance() { if (! self::$instance instanceof self) { self::$instance = new self(); } return self::$instance; } }
Single item means that you can only operate the same instance. It takes too many words to talk about this. Since you know the singleton mode, just go to the explanation of that one.
The destructor is the code that is called when the object is destroyed.
When this object is used up, the statements in this function will be automatically executed.
Your object has not been used up for the entire file. It will only be used up after outputting 55555. Because it is called twice, there are two ones, two and three at the end! Hope to adopt it!
The above is the detailed content of PHP destructor problem?. For more information, please follow other related articles on the PHP Chinese website!