Home > Backend Development > PHP Tutorial > Analysis of destructor examples of simulated classes in php4

Analysis of destructor examples of simulated classes in php4

黄舟
Release: 2023-03-12 10:50:01
Original
1065 people have browsed it

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");
Copy after login

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"; //覆盖对象变量
Copy after login

$ 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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template