概要
static::とself::はクラスのスタティックメソッドを指すときに使えるが、それぞれ以下のような違いがある。
staticはそれが実行されるときのクラスを指すselfはそれが定義されたときのクラスを指す
準備
以下のようにParentClassとそれを継承したChildClassを準備する。
- いずれも同じ名前の
staticメソッドstatic_method()を持つ - それぞれのクラスはインスタンスメソッド
parent_method()、child_method()を持つ- 何れの内容も同じで、
static::static_method()とself::static_method()を実行する
- 何れの内容も同じで、
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php class ParentClass { public static function static_method() { echo 'in ParentClass', PHP_EOL; } public function parent_method() { static::static_method(); self::static_method(); } } class ChildClass extends ParentClass { public static function static_method() { echo 'in ChildClass', PHP_EOL; } public function child_method() { static::static_method(); self::static_method(); } } |
クラスからstaticメソッドを呼ぶ
クラスからstaticメソッドを呼ぶと、当然それぞれに対応したstatic_method()が実行される。
|
1 2 3 4 5 |
ParentClass::static_method(); ChildClass::static_method(); // static method of Parent // static method of Child |
親クラスのメソッドから呼ぶ
親クラスのインスタンスを作って、インスタンスメソッドparent_method()内でstatic、selfでstatic_method()を呼び出す場合。
親クラスのstaticメソッドしか対象がないので、いずれの場合も親クラスのstatic_method()が実行される。
|
1 2 3 4 5 |
$parent = new ParentClass(); $parent->parent_method(); // in ParentClass // in ParentClass |
子クラスのメソッドから呼ぶ
子クラスのインスタンスを作って、インスタンスメソッドchild_method()内でstatic、selfでstatic_method()を呼び出す場合。
static、selfとも子クラスを指し、子クラスのインスタンスメソッドが実行される。
|
1 2 3 4 5 |
$child = new ChildClass(); $child->child_method(); // in ChildClass // in ChildClass |
子クラスで親クラスのメソッドから呼ぶ
子クラスのインスタンスを作って、継承元の親クラスのインスタンスメソッドparent_method()からstatic、selfでstatic_method()を呼び出す場合。
|
1 2 3 4 5 |
$child = new ChildClass(); $child->parent_method(); // in ChildClass // in ParentClass |
staticは実行時のクラスを指すため、Childクラスのstatic_method()が実行される。
一方selfは定義時のクラスを指すため、parent_method()が定義されたParentClassのstatic_method()が実行される。