Re: [PHP-DEV] Operator overloading for userspace objects

This is only part of a thread. view whole thread
February 6, 2020 20:29 (Chase Peeler)
On Fri, Jan 31, 2020 at 10:55 AM Ben Ramsey <> wrote:

> > Also, I want to reiterate: Any of these operations MUST be designed to > return a new value, never modify in place. These operators only make sense > on value objects, not service objects, and value objects should be > immutable. > > I completely agree. This was the gist of my earlier comments. > > Maybe we should resurrect discussion of the immutable classes and > properties RFC: > > If we add the ability to specify immutability, then we can enforce in the > engine that the left and right operands must be immutable. > > For example: > > public function __add(immutable $left, immutable $right); > > Cheers, > Ben > > Ideally, I don't think the items have to be immutable. Here is a silly
use-case: public function __add($left,$right){ $left->operatedOn++; $right->operatedOn++; return $left->value + $right->value; } However, given the nature of operator overloading, I think the users should EXPECT what they pass in will not be changed, unless they explicitly pass by reference. This means we'd have to "change the rules" for operator overloading magic methods, where objects are passed by value unless explicitly passed by reference ( public function __add(&$left, &$right) ). I think that is an even worse idea! So, I think you really have two options. Change the rules so that even objects are passed by value in this specific circumstance, and there is no ability to pass by reference. I still don't like this, because it changes the rules for only a specific scenario, but I think it's a better option than the one above, as well as a better option than allowing mutable objects 100% of the time - although, I'm not totally against spelling out in the documentation "Don't modify the items passed in or you'll get unexpected results!" The other options is the immutability RFC. This doesn't change the rules - it just adds a new rule. I don't see in that RFC, though, anything about the immutable type hints. That's really the only thing that I think is applicable to operator overloading. -- Chase Peeler