On 15 Jul 2014, at 19:59, Rowan Collins <rowan.coll...@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/ -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php