Hi Tim, Jordan,

On Fri, Apr 5, 2024 at 1:00 PM Tim Düsterhus <t...@bastelstu.be> wrote:
Hi

On 4/5/24 21:42, Saki Takamachi wrote:
> The only solution I can think of at the moment is to impose the constraint that
> when computing operator overloading, if the operands are both objects, they must
> be of the exact same class.

Even that would allow for confusing behavior:

     class MyNumber extends Number {
         private $importantMetadata;

         public function doSomething() {
             $this->importantMetadata = random_int(1, 100);
         }
     }

     $a = new MyNumber(5);
     $a->doSomething();
     $b = new MyNumber(10);
     $b->doSomething();

     $what = $a + $b;

What should be the value of $what->importantMetadata be? The property is
private, so as a user adding two of MyNumber would not even be able to
manually fix it up with the correct value, thus requiring the addition
of a "fixup" method that fixes the internal state of the object,
possibly even lacking the necessary information to properly fix up the
state, because it does not know which operations lead to the state.

Best regards
Tim Düsterhus

That is an absurd example. Why would anyone use inheritance for that class design? If what you are arguing is "if you look at use cases where composition is clearly the correct choice then inheritance causes problems", then I'm not sure what the point of the discussion is.

Jordan

One of the points Tim makes that actually matters is how to get user-defined properties on child classes to be carried over to new instances when operators are used to calculate them. (It doesn't really matter that the property is private.)

For example, suppose you define a tax rate in a child class.

My country currently has a mix of 10% and 8% tax rates, so the tax rate property could contain either 8 or 10.

The question here is, if add objects with different tax rates, what should the tax rate of the resulting object be? It may be that we shouldn't calculate objects with different tax rates in the first place, but we need to clarify the behavior when we do actually do so.

I've come up with a few options, but none of them are particularly smart. In fact, it's a very bad idea...

- If a child class has its own properties, their values ​​must match exactly before any calculations can be performed using operators.
- Properties defined in child classes are always uninitialized when calculated by operators.
- Always apply the state of the left operand

Also, as I was thinking about this, I realized that $roundMode has the same problem. When calculating with an operator, I needed to consider what should happen if two objects have different $roundModes.

I'll try to think of some more good ideas, but if you have any suggestions, please let me know.

Regards.

Saki

Reply via email to