PHPOOP-デストラクタ
PHP -__ destruct関数
オブジェクトが破棄されるか、スクリプトが停止または終了すると、デストラクタが呼び出されます。
関数を作成する__destruct()
と、PHPはスクリプトの最後にこの関数を自動的に呼び出します。
destruct関数は2つのアンダースコア(__)で始まることに注意してください!
以下の例には、クラスからオブジェクトを作成するときに自動的に呼び出される__construct()関数と、スクリプトの最後に自動的に呼び出される__destruct()関数があります。
例
<?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");
?>
もう一つの例:
例
<?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");
?>
ヒント:コンストラクタとデストラクタはコードの量を減らすのに役立つため、非常に便利です。