On 08/08/2021 08:41, Jordan LeDoux wrote:
Off the top of my head here are some of the use cases that I think benefit
greatly from this:
- Complex number objects
- Fractions objects
- Matrix objects (math)
- Vector objects (math)
- Time/Date intervals
- Collections
- Arbitrary precision numbers (which are usually represented as a string in
PHP)
I think that although mathematical libraries feel like a natural
example, they're actually rather a small niche in the world of PHP, so
not a great advert for the feature. Collections are not necessarily a
great example either, since defining "+" to mean "combine these two
collections in some type-specific way" is the kind of broad overloading
which is often controversial.
An example which I think would be applicable to many more PHP users is a
"Money" type, with a value, a currency, and perhaps a precision. It's
also an interesting example where all the mathematical operators can be
implemented, but restricted to certain combinations of types, and even
combinations of values.
A real-life example from a C# project has the following overloads
(syntax tweaked to be more PHP-like):
public static operator - (Money $m1, Money $m2): Money
public static operator + (Money $m1, Money $m2): Money
public static operator / (Money $money, float $divisor): Money //
fraction of a Money value
public static operator / (Money $m1, Money $m2): float // ratio of two
Money values
public static operator * (Money $money, float $multiple): Money // note
[Money * Money] is not defined
public static operator < (Money $m1, Money $m2): bool
public static operator > (Money $m1, Money $m2): bool
public static operator == (Money $m1, Money $m2): bool
public static operator != (Money $m1, Money $m2): bool // defined as
!($m1 == $m2)
All operators which take two Money values throw an exception if they
have different currencies.
The [float * Money] case isn't overloaded here, although it would make
sense; I don't know if that's because it can't be in C#'s overload
system, or just that it is missing from this implementation.
Since even a single operator interface can't guarantee that all inputs
will have a valid output, I remain unconvinced that implementing 8
different interfaces for the above is any better than implementing one
interface and stubbing the parts that have no valid inputs.
Regards,
--
Rowan Tommins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php