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());

preferences:
25.95 ms | 402 KiB | 5 Q