解析PHP5析构函数的具体使用方法

开发 后端
我们在学习PHP语言的时候,可能会发现,它的构造函数与析构函数与以往有些许不同。比如PHP5析构函数被定义为一个名为__destruct()的函数。

在升级版的PHP5中,都有构造函数与PHP5析构函数。但是在具体的实际操作中,他们的功能和使用方式已经和普通的函数方式有所不同。每当实例化一个类对象时,都会自动调用这个与类同名的函数,使对象具有与生俱来的一些特征。

#t#在PHP5中,则使用__construct()来命名构造函数,而不再是与类同名,这样做的好处是可以使构造函数独立于类名,当类名改变时,不需要在相应的去修改构造函数的名称。

与构造函数相反,在PHP5中,可以定义一个名为__destruct()的函数,称之为PHP5析构函数,PHP将在对象在内存中被销毁前调用析构函数,使对象在彻底消失之前完成一些工作。对象在销毁一般可以通过赋值为null实现。

<?php 
/*  
 * Created on 2009-11-18  
 *  
 * To change the template for this generated file go to  
 * Window - Preferences - PHPeclipse - PHP - Code Templates  
 */  
 class student{  
  //属性  
  private $no;  
  private $name;  
  private $gender;  
  private $age;  
    
  private static $count=0;  
  function __construct($pname)  
  {  
   $this->name = $pname;  
   self::$count++;  
  }  
    
  function __destruct()  
  {  
   self::$count--;  
  }  
    
  static function get_count()  
  {  
   return self::$count;  
  }  
 }  
   
 $s1=new student("Tom");  
 print(student::get_count());  
   
 $s2=new student("jerry");  
 print(student::get_count());  
   
 $s1=NULL;  
 print(student::get_count());  
   
 $s2=NULL;  
 print(student::get_count());  
?> 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.

上面这段代码就是PHP5析构函数的具体使用方法,希望对大家有所帮助。

责任编辑:曹凯 来源: CSDN
相关推荐

2009-12-07 16:52:59

PHP函数getima

2009-11-24 16:28:41

PHP5魔术函数

2009-11-25 10:02:27

PHP会话Sessio

2009-11-26 15:23:24

PHP函数ereg()

2009-11-26 19:05:04

PHP函数explod

2009-12-01 19:02:20

PHP取整函数

2009-12-02 18:51:12

PHP分页类

2009-11-18 18:33:23

Linux PHP5安

2009-11-30 15:00:19

PHP加密解密函数au

2009-11-24 19:25:32

PHP关联数组

2009-12-01 17:00:49

PHP变量

2009-11-24 15:50:09

PHP上传类uploa

2009-12-04 17:16:41

PHP析构函数

2009-11-30 17:43:54

PHP split()

2009-12-01 18:02:41

PHP表单数组

2009-12-11 17:33:56

PHP5常用函数

2009-11-23 19:33:12

PHP5多态性

2011-08-29 15:58:51

Lua函数

2009-11-23 20:00:25

PHP5接口PHP5抽象类

2009-11-16 16:54:00

PHP构造函数
点赞
收藏

51CTO技术栈公众号