A project I recently worked on was based on PHP4. I am used to PHP5 facing objects. Facing PHP4, I will inevitably have a lot of dissatisfaction:
does not support public, static, private, protected keywords, the most depressing thing is that destructor is not supported:
This article will use PHP's register_shutdown_function to simulate the destructor of a class in PHP4 Function
We register the destructor in the constructor:
class sample{ var $identified; function sample($iden){ $this->identified = $iden; register_shutdown_function(array(&$this, 'destructor')); //模拟析构函数 } function destructor(){ error_log("destructor executing, Iden is ". $this->identified); unset($this); } } $sample = new sample("laruence"); $sample2 = new sample("HuiXinchen");
Execute this script, you will find that the object's destructor is correctly called.
Because we used the $this keyword when registering the closing function, even if your opposite variable is overwritten, the destructor can be called correctly, such as:
class sample{ var $identified; function sample($iden){ $this->identified = $iden; register_shutdown_function(array(&$this, 'destructor')); //模拟析构函数 } function destructor(){ error_log("destructor executing, Iden is ". $this->identified); unset($this); } } $sample = new sample("laruence"); $sample = "laruence"; //覆盖对象变量
$ The sample is overwritten, but when you run this script, you will find that the destructor can still be called correctly. Even the following code:
class sample{ var $identified; function sample($iden){ $this->identified = $iden; register_shutdown_function(array(&$this, 'destructor')); //模拟析构函数 } function destructor(){ error_log("destructor executing, Iden is ". $this->identified); unset($this); } } $sample = new sample("laruence"); unset($sample);
The destructor can still be called correctly.
The above is the detailed content of Analysis of destructor examples of simulated classes in php4. For more information, please follow other related articles on the PHP Chinese website!