On 28/07/2025 16:32, Larry Garfield wrote:
Even without the precision loss question, such a function would be very useful when
parsing input data of unknown type (and thus is a string). "Can I cast this string
to an int to use with an int parameter without any loss" is currently not as simple
as it ought to me. Providing a single standardized function for that would be most
welcome.
The name is quite long though. 🙂
This is basically where I was going with "can_lossless_cast". The reason
I went with a generic-like syntax is because it makes it exntendible to
any representable type, without an ever-growing list of long names like
"is_representable_as_int_or_float".
I also see it as part of a wider set of missing cast functions; for any
value V and type T:
1. Is V of type T?
2. Can V be safely converted to T (for some definition of "safe")?
3. If V can safely be converted to T, give that result; otherwise, throw
an Exception|Error
4. If V can safely be converted to T, give that result, else return null
5. If V can safely be converted to T, give that result, else return a
default value of type T
Given (5), you can implement (2), (3), and (4), but not elegantly,
particularly if null is a valid output, e.g.:
( cast<?int>($v, default: false) !== false ) ? cast<?int>($v, default:
false)Â : throw new TypeError('Not null, and not castable to int');
vs
cast_or_throw<?int>($v)
I've got a half-drafted RFC around this, but stalled on a) naming; and
b) what a "safe" cast means for different types. It seems like both
problems have already come to light in this thread.
--
Rowan Tommins
[IMSoP]