PHP Velho Oeste 2024

コンストラクタ

コンストラクタは、new によりクラスの新しいインスタンスを作成する際に自動的にコールされるクラス関数です。 ある関数が、クラス名と同じ名前を有している場合にコンストラクタになります。 コンストラクタが存在しない場合、 もし基底クラスのコンストラクタが存在すれば、それがコールされます。

<?php
// PHP 3 および PHP 4で動作します
class Auto_Cart extends Cart
{
    function 
Auto_Cart()
    {
        
$this->add_item ("10"1);
    }
}
?>

この例は、Cart にコンストラクタを加えたクラス Auto_Cart を定義しています。 このコンストラクタは、"new" により新しい Auto_Cart が作成される度に 籠に10番の物を一つ保持するように初期化します。コンストラクタは、オ プションとして引数をとります。これにより、コンストラクタは非常に便 利なものとなります。このクラスをパラメータが指定されない場合でも使 用できるようにするには、コンストラクタに指定する全てのパラメータに デフォルト値を指定してください。

<?php
class Constructor_Cart extends Cart
{
    function 
Constructor_Cart($item "10"$num 1)
    {
        
$this->add_item ($item$num);
    }
}
 
// しつこいが、前の例と同じものを買う
$default_cart = new Constructor_Cart;
 
// 実際に買うものをカゴに入れる...
$different_cart = new Constructor_Cart("20"17);
?>

@newのようにコンストラクタで発生するエラーの 出力を抑制するために@演算子を使用することが 可能です。例:@new

<?php
class A
{
    function 
A()
    {
        echo 
"Aのコンストラクタです<br>\n";
    }

    function 
B()
    {
        echo 
"クラスAのBという名前の通常の関数<br>\n";
        echo 
"Aのコンストラクタではありません<br>\n";
    }
}

class 
extends A
{
}

// これにより、B() がコンストラクタとしてコールされます。
$b = new B;
?>

クラスAの関数 B() は、意図されていない場合でも突然クラスB の コンストラクタになってしまいました。PHP 4 は、この関数が クラスBで定義されているかとかその関数が継承されているかどうかは 考慮しません。

警告

PHP では派生クラスのコンストラクタから基底クラスの コンストラクタを自動的にコールすることはできません。 上流のコンストラクタを適切にコールするように伝播させることは あなたの責任でやるべきことです。

デストラクタは、unset()またはスコープから でることにより、オブジェクトが破棄される度に自動的にコールされる関数です。 PHPにはデストラクタはありません。デストラクタの機能の多くを シミュレーションするには、代わりに register_shutdown_function() を使用します。

add a note add a note

User Contributed Notes 2 notes

up
0
Anonymous
9 years ago
I only just noticed this page is specifically referring to PHP 4, so I'd suggest changing
"There are no destructors in PHP."
to
"There are no destructors in PHP 4. Support for destructors was added in PHP 5."
up
0
Anonymous
9 years ago
"There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors. "

I thought this was a particularly strange statement, seeing as that I use __construct() en __destruct() the whole time. And surely, from http://php.net/manual/en/language.oop5.decon.php we can read this:

"void __destruct ( void )
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. "

And even:
"The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing."

So PHP definitely supports destructors.
To Top