An example analysis of the destructor of simulation class in PHP4

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.