一起源码网

  • www.171739.xyz
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 4891|回复: 1
打印 上一主题 下一主题

php4中模拟类的析构函数实例分析

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-3-17 18:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
最近做的一个项目是基于PHP4的, 习惯了PHP5的面对对象,面对PHP4,难免会有很多不爽:

不支持public, , private, protected关键字, 最郁闷的是,不支持:

本文就将借助PHP的register_shutdown_function来在PHP4中模拟类的析构函数

我们在中, 注册析构函数:

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");

执行这个脚本, 你会发现, 对象的析构函数被正确的调用了.
因为我们在注册关闭函数的时候,使用了$this关键字, 所以,即使你的对面变量被覆盖了, 析构函数也是可以被正确调用的,比如:

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

$sample被覆盖,但是运行这段脚本,你会发现析构函数还是可以被正确调用. 即使是下面的代码:

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);

析构函数还是可以被正确调用.

分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

13

帖子

123

积分

注册会员

Rank: 2

积分
123
沙发
发表于 2022-9-8 14:08 来自手机 | 只看该作者
免费网站java源码大全
回复

使用道具 举报

一起源码让程序更轻更快

www.171739.xyz

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表