>> a) The DateTimeImmutable class extends the DateTime class. Why was
>> this done this way? Both classes are incompatible (as in the
>> inheritance violates LSP). E.g. if you hint against DateTime, then
>> passing in DateTimeImmutable will not work (as the behavior is
>> different). The same also applies the other way around (DateTime
>> extending DateTimeImmutable). Imho a mutable and an immutable variant
>> of a class can't reasonably extend from one another, so I'm not sure
>> why this was done.
>
> It was mostly done so that methods and code accepting do not need
> signature changes. In many cases library code would accept a DateTime,
> call modify and return the changed object - not realizing that the
> original object was changed as well causes issues with calling code. By
> having DateTimeImmutable extend DateTime they can continue to pass them
> in, without having to change library code at all.

What if they return the same object knowing that `modify` actually
modifies the object? I personally would have done that except in the
lucky situation that I used it in the return statement:

    return $timestamp->modify('+30 days');

Then I'd luckily work with DateTimeImmutable.

---

While I personally think DateTime should have been immutable from the
beginning, I don't think it's in PHP's best interest to try to fix
this particular problem by introducing DateTimeImmutable.

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to