PHP OOP - 解構函式
PHP - __destruct() 函式
當物件被銷燬,或指令碼停止或退出時,解構函式會被呼叫。
如果您建立了一個 __destruct()
函式,PHP 將在指令碼結束時自動呼叫此函式。
請注意,解構函式以兩個下劃線(__)開頭!
下面的示例包含一個 __construct() 函式(在建立類的物件時自動呼叫),以及一個 __destruct() 函式(在指令碼結束時自動呼叫)。
示例
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "水果是 {$this->name}。";
}
}
$apple = new Fruit("Apple");
?>
自己動手試一試 »
另一個例子
示例
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "水果是 {$this->name} 顏色是 {$this->color}。";
}
}
$apple = new Fruit("Apple", "red");
?>
自己動手試一試 »
提示: 建構函式和解構函式非常有用,可以幫助減少程式碼量!