PHP 構(gòu)造函數(shù)
構(gòu)造函數(shù)是一種特殊的方法。主要用來在創(chuàng)建對(duì)象時(shí)初始化對(duì)象, 即為對(duì)象成員變量賦初始值,在創(chuàng)建對(duì)象的語(yǔ)句中與?new?運(yùn)算符一起使用。
PHP 5 允許開發(fā)者在一個(gè)類中定義一個(gè)方法作為構(gòu)造函數(shù),語(yǔ)法格式如下:
void __construct ([ mixed $args [, $... ]] )
在上面的例子中我們就可以通過構(gòu)造方法來初始化 $url 和 $title 變量:
function __construct( $par1, $par2 ) {
$this->url = $par1;
$this->title = $par2;
}
現(xiàn)在我們就不需要再調(diào)用 setTitle 和 setUrl 方法了:
使用構(gòu)造函數(shù)前
$runoob = new Site;
$taobao = new Site;
$google = new Site;
// 調(diào)用成員函數(shù),設(shè)置標(biāo)題和URL
$runoob->setTitle( "菜鳥教程" );
$taobao->setTitle( "淘寶" );
$google->setTitle( "Google 搜索" );
$runoob->setUrl( 'www.runoob.com' );
$taobao->setUrl( 'www.taobao.com' );
$google->setUrl( 'www.google.com' );
使用構(gòu)造函數(shù)后
$runoob = new Site('www.runoob.com', '菜鳥教程');
$taobao = new Site('www.taobao.com', '淘寶');
$google = new Site('www.google.com', 'Google 搜索');
// 調(diào)用成員函數(shù),獲取標(biāo)題和URL
$runoob->getTitle();
$taobao->getTitle();
$google->getTitle();
$runoob->getUrl();
$taobao->getUrl();
$google->getUrl();
析構(gòu)函數(shù)
析構(gòu)函數(shù)(destructor) 與構(gòu)造函數(shù)相反,當(dāng)對(duì)象結(jié)束其生命周期時(shí)(例如對(duì)象所在的函數(shù)已調(diào)用完畢),系統(tǒng)自動(dòng)執(zhí)行析構(gòu)函數(shù)。
PHP 5 引入了析構(gòu)函數(shù)的概念,這類似于其它面向?qū)ο蟮恼Z(yǔ)言,其語(yǔ)法格式如下:
void __destruct ( void )
實(shí)例
<?php
class MyDestructableClass {
function __construct() {
print "構(gòu)造函數(shù)n";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "銷毀 " . $this->name . "n";
}
}
$obj = new MyDestructableClass();
?>
執(zhí)行以上代碼,輸出結(jié)果為:
構(gòu)造函數(shù)
銷毀 MyDestructableClass