技术开发 频道

PHP开发经典教程 (Part7):面向对象编程

析构器 

    就像存在构造器一样,因此析构器也是存在的。析构器是一种对象方法,当对内存中的一个对象的最后引用被销毁时调用该对象方法,且它们通常被分派了清理工作的任务(例如,关闭数据库连接或者文件,销毁一个会话等等)。析构器仅在PHP 5中可用,而且必须被命名为__destruct()。下面是一个对其进行说明的例子:

<?php // PHP 5 // class definition class Bear { // define properties public $name; public $weight; public $age; public $sex; public $colour; // constructor public function __construct() { $this->age = 0; $this->weight = 100; $this->colour = "brown"; } // destructor public function __destruct() { echo $this->name." is dead. He was ".$this->age."
years old and
".$this->weight." units heavy. Rest in peace! "; } // define methods public function eat($units) { echo $this->name." is eating ".$units." units of food... "; $this->weight += $units; } public function run() { echo $this->name." is running... "; } public function kill() { echo $this->name." is killing prey... "; } } // create instance of Bear() $daddy = new Bear; $daddy->name = "Daddy Bear"; $daddy->age = 10; $daddy->kill(); $daddy->eat(2000); $daddy->run(); $daddy->eat(100); ?>


    这里,一旦脚本执行结束,对于变量$daddy的引用就不再存在了,因此,析构器将被自动调用。程序的输出就像下面这样:

Daddy Bear is killing prey... Daddy Bear is eating 2000 units of food... Daddy Bear is running... Daddy Bear is eating 100 units of food... Daddy Bear is dead. He was 10 years old and 2200 units heavy. Rest in peace!
0
相关文章