On 01/02/2016 08:14 PM, Sara Golemon wrote:
Patricio Tarantino has asked me to help him propose Operator
Overloading in PHP 7.1 (based in part on my operator extension in
PECL). I think we can expose this to usespace as magic methods with
very little overhead (the runtime check and dispatch is already there,
after all).
I do think that the "Future Expansion" section bears following through
with as well, but the basic set of methods already hooked for GMP
would be a nice start.
https://wiki.php.net/rfc/operator-overloading
-Sara
I'm really torn here.
First off, IF PHP were to adopt such overloading, I would much prefer
special interfaces over magic methods. It's simply far more
self-documenting and reduces the difference between user-space and
PHP-space features. (And I'd be all for migrating the current magic
methods to that, too, if we wanted consistency.)
That said... as Stas notes the can of worms this entails is quite
large. I've started thinking more in terms of pure value objects in the
past year (PSR-7-inspired), and for those, having richer operations can
be quite useful. DateTime, for instance, supports > and <, which would
be similarly helpful on other value objects. Think money for a good
example, or object-based collections. It also serves to improve the
type system, as a Currency object could allow itself to be added iff the
other Currency object was in the same denomination.
That said, the potential for magic "WTF were you thinking?" there is
also scarily large. Stas hinted at an example, as does the RFC itself.
From the first example:
public function __add($rhs) {
$ret = clone $this;
if ($rhs instanceof Complex) {
$ret->real += $rhs->real;
$ret->imaginary += $rhs->imaginary;
} else {
$ret->real += (int)$rhs;
}
return $ret;
}
That all seems reasonable. Return a new object that is the result of
adding the real and imaginary components together. Cool. I give it
about 8 minutes before someone forgets to clone $this first and just
starts returning $this, in which case you now have an addition operator
that both modifies a value in place *and* returns itself. I then give it
about 4 minutes after that before someone tries to defend that as a good
practice, and now we have a large cadre of people who will insist that
$c = $a + $b;
modifying $a along the way is "totally a legit thing, it's a performance
optimization, stop being so pedantic telling me I shouldn't do that!"
(Come on, you know that's going to happen.) The worst-case scenario
there is not guaranteed, but it still scares the bejeebus out of me.
So for the moment, I'm tentatively -1. Perhaps limiting it for now to
the obviously immutable operators, ie the comparison operators only,
would be a safe babystep?
--Larry Garfield