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

This is an error 500

Value for `_results` contains invalid data `array`


preferences:
164.47 ms | 1488 KiB | 13 Q