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