Andrea Faulds wrote (on 15/07/2014):
It’s a shame Nikita’s Exceptions in the Engine RFC failed, as being able to do
this would be nice:
try {
$foo = (int!)$foo;
} catch (RecoverableError) {
$foo = 1;
}
Perhaps some sort of similar syntax? `(int!)$foo else 0`?
I was thinking the same thing myself as I wrote it. My main disagreement
with the EngineExceptions as they were proposed was that I think
meaningful sub-classes are a must:
try {
$foo = (int!)$foo;
} catch (UnsafeCastException $e) {
$foo = 1;
}
My other thought was to have a syntax for "is this cast safe?", e.g.
(int?) but the more I play with it, the more ugly it feels:
if ( ! (int?)$foo ) {
$foo = 1;
}
I'd still like to see some readable way of writing that, though. The
only built-in function I know of which comes close is filter_var(),
which feels like a bit of a sledgehammer:
if ( false === filter_var($foo, FILTER_VALIDATE_INT) ) {
throw new UnsafeCastException;
}
Or, to implement a "safe cast", and catch the error case:
if ( false === $foo = filter_var($foo, FILTER_VALIDATE_INT) ) {
$foo = 1;
}
Yuck! :P
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php