PHP課程
/ 析構(gòu)函數(shù)
析構(gòu)函數(shù)
PHP - __destruct 函數(shù)
當(dāng)對(duì)象被銷毀或腳本停止或退出時(shí),會(huì)調(diào)用析構(gòu)函數(shù)。
如果您創(chuàng)建一個(gè) __destruct()
函數(shù),PHP 將在腳本結(jié)束時(shí)自動(dòng)調(diào)用此函數(shù)。
請(qǐng)注意,析構(gòu)函數(shù)以兩個(gè)下劃線(__
)開(kāi)頭!
下面的例子有一個(gè) __construct()
函數(shù),當(dāng)您從類中創(chuàng)建一個(gè)對(duì)象時(shí)會(huì)自動(dòng)調(diào)用它,以及一個(gè) __destruct()
函數(shù),它會(huì)在腳本結(jié)束時(shí)自動(dòng)調(diào)用:
實(shí)例
<?php class Fruit { public $name; public $color; function __construct($name) { $this->name = $name; } function __destruct() { echo "The fruit is {$this->name}."; } } $apple = new Fruit("Apple"); ?>運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
另一個(gè)例子:
實(shí)例
<?php class Fruit { public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } function __destruct() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } $apple = new Fruit("Apple", "red"); ?>運(yùn)行實(shí)例 ?
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
提示:由于構(gòu)造函數(shù)和析構(gòu)函數(shù)有助于減少代碼量,因此它們非常有用!