コンストラクタとデストラクタは下のように書くことで実装されます
<?php
class MyClass{
function __construct(){
echo "Constrauct Called!\n";
}
function __destruct(){
echo "Destruct Called\n";
}
}
$myclass1 = new MyClass();
実行結果はこうなります。
Constrauct Called! Destruct Called
コンストラクタ自体はクラスがインスタンス化されたときに実行されます。
デストラクタは特定のオブジェクトを参照するリファレンスがなくなったときにコールされますがデストラクタはスクリプトの実行を止めたときにもコールされます。 以下の例で比べてみましょう。
参照するリファレンスがなくなったとき
<?php
class MyClass{
public $text = null;
function __construct($text){
$this->text = $text;
echo $this->text . " Constrauct Called!\n";
}
function __destruct(){
echo $this->text . " Destruct Called\n";
}
}
$myclass1 = new MyClass("The 1st");
$myclass1 = null;
$myclass2 = new MyClass("The 2nd");
二番目のクラスがインスタンス化される前に最初のクラスにNULLが渡されてデストラクトされているので出力はこうなります。
The 1st Constrauct Called! The 1st Destruct Called The 2nd Constrauct Called! The 2nd Destruct Called
スクリプトの実行を止めたとき
<?php
class MyClass{
public $text = null;
function __construct($text){
$this->text = $text;
echo $this->text . " Constrauct Called!\n";
}
function __destruct(){
echo $this->text . " Destruct Called\n";
}
}
$myclass1 = new MyClass("The 1st");
// $myclass1 = null;
$myclass2 = new MyClass("The 2nd");
出力はこうなります。先ほどとの出力の順番を見比べるとデストラクトのタイミングが違うことがわかりますね。ちなみにスクリプトの実行を止めたときにデストラクトされるオブジェクトの順番はインスタンス化した順番に関係なく任意にきまります。
The 1st Constrauct Called! The 2nd Constrauct Called! The 2nd Destruct Called The 1st Destruct Called


