解析PHP5析構(gòu)函數(shù)的具體使用方法
在升級(jí)版的PHP5中,都有構(gòu)造函數(shù)與PHP5析構(gòu)函數(shù)。但是在具體的實(shí)際操作中,他們的功能和使用方式已經(jīng)和普通的函數(shù)方式有所不同。每當(dāng)實(shí)例化一個(gè)類對(duì)象時(shí),都會(huì)自動(dòng)調(diào)用這個(gè)與類同名的函數(shù),使對(duì)象具有與生俱來的一些特征。
#t#在PHP5中,則使用__construct()來命名構(gòu)造函數(shù),而不再是與類同名,這樣做的好處是可以使構(gòu)造函數(shù)獨(dú)立于類名,當(dāng)類名改變時(shí),不需要在相應(yīng)的去修改構(gòu)造函數(shù)的名稱。
與構(gòu)造函數(shù)相反,在PHP5中,可以定義一個(gè)名為__destruct()的函數(shù),稱之為PHP5析構(gòu)函數(shù),PHP將在對(duì)象在內(nèi)存中被銷毀前調(diào)用析構(gòu)函數(shù),使對(duì)象在徹底消失之前完成一些工作。對(duì)象在銷毀一般可以通過賦值為null實(shí)現(xiàn)。
- <?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());
- ?>
上面這段代碼就是PHP5析構(gòu)函數(shù)的具體使用方法,希望對(duì)大家有所幫助。