/**
* Cast to int, fail if not a valid integer
* @throws \UnexpectedValueException
* @param mixed $thing
* @return int
*/
function as_int($thing): int
{
$int = filter_var($thing, \FILTER_VALIDATE_INT);
if ($int === false) {
throw new \UnexpectedValueException("Value is not an integer.");
}
return $int;
}
Thus the critique against PHP that is lacks a proper integer parsing function is simply not true, filter_var has been part of PHP since 5.2 released in 2006, over 16 years ago. filter_var works as advertised, because I use it almost every time i write PHP and that is to mostly to parse integers but sometimes also for other types. And I don't even wrap it with my own as_int function, using it inline with an simple if-check afterwards is actually cleaner. And if you prefer that filter_var returns null on failure instead of false you can simply add FILTER_NULL_ON_FAILURE as the third argument to filter_var.And this is the recurring thing with PHP critique, vast majority of the time it just in imagination because nobody bothers to look it up.