Recently done a project is based on PHP4, accustomed to PHP5 face object, face PHP4, inevitably will have a lot of uncomfortable:
Does not support the public, static, private, protected keywords, the most depressing is that the destructor is not supported:
This article will use PHP's register_shutdown_function to simulate a class's destructor in PHP4
In the constructor, we register the destructor:
Class sample{ var $identified; Function sample ($iden) { $this->identified = $iden; Register_shutdown_function (Array (& $this, ' destructor ')); Simulate destructor} function destructor () { error_log ("destructor executing, Iden is"). $this->identified); Unset ($this); }} $sample = new Sample ("Laruence"); $sample 2 = new sample ("Huixinchen");
Execute this script and you will find that the destructor of the object is called correctly.
Because we used the $this keyword when registering the close 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 ')); Simulate destructor} function destructor () { error_log ("destructor executing, Iden is"). $this->identified); Unset ($this); }} $sample = new Sample ("Laruence"); $sample = "Laruence"; overriding object variables
$sample is overwritten, but by running the script, you will see 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 ')); Simulate destructor} function destructor () { error_log ("destructor executing, Iden is"). $this->identified); Unset ($this); }} $sample = new Sample ("Laruence"); Unset ($sample);
Destructors can also be called correctly.