3v4l.org

run code in 300+ PHP versions simultaneously
<?php interface I { public function a(int $a): string; } Class C implements I { public function a(int|string $a): string { return "foo"; } } class D implements I { public function a(int $a): string { return "foo"; } } /** * `test` from previous example (https://3v4l.org/5YPdg) does not respect I. * It calls with a string instead of an int (which is what I requires), thus the $subject->a() * call will fail at runtime for any implementation of I that doesn't widen the type. */ function ignores_i(I $subject) { print $subject->a("beep"); } /** * This implementation respects the interface--the $subject->a() call will * _never_ result in a type error at runtime */ function respects_i(I $subject) { print $subject->a(123); } /** * Widening int => int|string _is_ useful, becacuse we can also write code against * this concrete type, and here we _can_ safely pass a string. */ function uses_concrete_type(C $subject) { $subject->a("beep"); } respects_i(new C()); // works respects_i(new D()); // works uses_concrete_type(new C()); // works ignores_i(new C()); // works ignores_i(new D()); // type error
Output for 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
foofoofoo Fatal error: Uncaught TypeError: D::a(): Argument #1 ($a) must be of type int, string given, called in /in/qMZOH on line 25 and defined in /in/qMZOH:14 Stack trace: #0 /in/qMZOH(25): D->a('beep') #1 /in/qMZOH(49): ignores_i(Object(D)) #2 {main} thrown in /in/qMZOH on line 14
Process exited with code 255.

preferences:
45.16 ms | 406 KiB | 5 Q