3v4l.org

run code in 300+ PHP versions simultaneously
<?php class A { function method1(): string { return 'hello'; } } class B { function method2(): string { return 'world'; } } final class SomeKindOfException extends OutOfBoundsException { public static function forMismatchingRequirements(mixed $value, string $type): self { return new self(sprintf('Expected value of type "%s", got "%s"', $type, get_debug_type($value))); } } /** * @template T of object * @param class-string<T> $type * @throws SomeKindOfException * @return T */ function typed(mixed $value, string $type): mixed { if (! $value instanceof $type) { throw SomeKindOfException::forMismatchingRequirements($value, $type); } return $value; } function expression1(): mixed { return new A(); } function expression2(): mixed { return new B(); } function expression3(): mixed { return new stdClass(); } var_dump(typed(expression1(), A::class)->method1()); var_dump(typed(expression2(), B::class)->method2()); var_dump(typed(expression3(), B::class)->method2());
Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.7
string(5) "hello" string(5) "world" Fatal error: Uncaught SomeKindOfException: Expected value of type "B", got "stdClass" in /in/iQPok:8 Stack trace: #0 /in/iQPok(20): SomeKindOfException::forMismatchingRequirements(Object(stdClass), 'B') #1 /in/iQPok(31): typed(Object(stdClass), 'B') #2 {main} thrown in /in/iQPok on line 8
Process exited with code 255.

preferences:
86.67 ms | 402 KiB | 61 Q