Re: [RFC] Scalar Type Hinting With Casts (re-opening)

From: Date: Tue, 15 Jul 2014 19:44:55 +0000
Subject: Re: [RFC] Scalar Type Hinting With Casts (re-opening)
References: 1 2 3 4 5 6 7 8 9  Groups: php.internals 
Request: Send a blank email to internals+get-75559@lists.php.net to get a copy of this message
On 15 Jul 2014, at 19:59, Rowan Collins <rowan.collins@gmail.com> wrote: > Or, to implement a "safe cast", and catch the error case: > > if ( false === $foo = filter_var($foo, FILTER_VALIDATE_INT) ) { > $foo = 1; > } > > Yuck! :P The patch and RFC introduce a new set of “safe” conversion functions which we could use for these safe casts. In fact, it makes normal casts use them too now, they just ignore the errors. PHP has pseudo-functions, maybe we could use that format? cast_int($foo)? Actually, perhaps the solution is an ahead-of-time check: if (safe_cast($foo, int)) { $bar = (int!)$foo; } else { $bar = 1; } Perhaps safe_int or something would be better. Anyhow, (int!) would error if the cast was unsafe, but as you'd checked ahead of time, it wouldn’t error here. That, or perhaps something with an optional argument: $bar = cast_int($foo, 1); // defaults to 1 if cast unsafe $bar = cast_int($foo); // unsafe cast But I don’t like that approach as it doesn’t match the nice (int!) syntax. This just occurred to me: $bar = (int?)$foo ? (int!)$foo : 1; I’m not sure if that’s horrible or brilliant. -- Andrea Faulds http://ajf.me/

« previous php.internals (#75559) next »