<?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);
}
- Output for 7.1.25 - 7.1.28, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- Expected int, got string
bool(false)
preferences:
169.57 ms | 403 KiB | 163 Q