Re: [RFC] Scalar Type Hinting With Casts (re-opening)
| From: | Rowan Collins | Date: | Tue, 15 Jul 2014 18:59:14 +0000 |
| Subject: | Re: [RFC] Scalar Type Hinting With Casts (re-opening) | ||
| References: | 1 2 3 4 5 6 7 8 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-75557@lists.php.net to get a copy of this message | ||
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 {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 (RecoverableError) {$foo = 1;} Perhaps some sort of similar syntax?(int!)$foo else 0?
$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