Numeric casts could emit a warning it they do not make sense
Description
(float) '1';
(float) '1.0';
(float) '';
(float) 'x'; // should always warn
(int) '1';
(int) '1.0';
(int) '';
(int) 'x'; // should always warn
https://3v4l.org/gDLOv
This is a feature request. The casts above are advised by many static analysers, but if added explicitly, there is currently no warning emit. They should at least emit a warning if the input is not numerical and the cast does not make sense.
As designed, casts just enforce type conversion; it's basically the programmer saying "I'm a big boy, I know what I'm doing". Changing that long-standing behavior would require the RFC process.
FWIW we at least have some warnings already when casting to strings.
https://3v4l.org/UsMnb
var_dump((string) []);
Warning: Array to string conversion in /in/UsMnb on line 3 string(5) "Array"
I do think casting a non-numeric string to ints is often indicative of an error. Either way, as Christoph mentioned, this would require an RFC.
While we warn when casting an array to a string, this is about preventing the whole class of arrays, and not specific patterns of arrays (like with strings where numerical ones would be allowed).
To get a checked cast of a string to a number, I'd recommend the one-char variant, prepending a + sign. Given that there is a short way to do a checked conversion to number (plus sign) - and a longer (the cast) unchecked version, I do not think there's a need for a change. In fact it's a good thing that there exists a (relatively easy) way to do unchecked casts "just squeeze that into a number". It's a safe way of doing that which existed since very old times and should stay.
A common use case for int casts is taking (possibly client-side validated) user inputs for example. You do not really want to break this common scenario.
his is about preventing the whole class of arrays, and not specific patterns of arrays
We also throw when casting non-stringable objects to strings, while stringable objects are obviously allowed.
"just squeeze that into a number". It's a safe way of doing that which existed since very old times and should stay.
Yeah, that's a valid concern. (int)$foo !== 0 is probably a common pattern when 0 is not a valid value.