3v4l.org

run code in 300+ PHP versions simultaneously
<?php namespace e { const string = 'string'; const int = 'int'; const float = 'float'; const bool = 'boolean'; /** * @template T * @param typename<T> $type * @return T */ function check($var, string $type) { if (\gettype($var) === $type) { return $var; } $check = \sprintf("is_", $type); if (\function_exists($check) && $check($var)) { return $var; } elseif (\is_a($var, $type)) { return $var; } throw new \Exception(\sprintf('Expected %s, got %s', $type, gettype($var))); } // hack : // function as<T>(mixed $var, typename<T> $type): T { // } } namespace { try { $var = 'string'; $var = e\check($var, e\int); } catch(\Exception $e) { echo $e->getMessage(), "\n"; } $var = false; $var = e\check($var, e\bool); \var_dump($var); }

preferences:
34.13 ms | 402 KiB | 5 Q