上級 › self:: で作ったインスタンスは継承先のサブクラスにならない(static:: との違い) › パターン2
self:: で作ったインスタンスは継承先のサブクラスにならない(static:: との違い)
戻り値の型を static と宣言したメソッドの中で new self() を使うと、呼び出し元がサブクラスであっても常に定義元のクラスのインスタンスが作られます。
1 <?php 2 class Animal { 3 public static function make(): static { 4 return new ______(); ^ 5 } 6 } 7 class Cat extends Animal {} 8 $obj = Cat::make(); 9 echo get_class($obj);
Fatal error: Uncaught TypeError: Animal::make(): Return value must be of type Cat, Animal returned in main.php:4
空欄を埋めて実行を通す
self::は定義されたクラス(Animal)に固定されます。呼び出し元のサブクラス(Cat)を返したい場合はstatic(遅延静的束縛)を使う必要があります。
次の問題