On Thu, Nov 17, 2022 at 11:47 AM Marco Pivetta <ocram...@gmail.com> wrote:
> ```php > <?php > > /* readonly */ class ImmutableCounter { > public function __construct(private readonly int $count) {} > public function add1(): self { return new self($this->count + 1); } > public function value(): int { return $this->count; } > } > > // assuming the proposed RFC is in place, this is now possible: > class MutableCounter extends ImmutableCounter { > public function __construct(private int $count) {} > public function add1(): self { return new self(++$this->count); } > public function value(): int { return $this->count; } > } > > $counter1 = new ImmutableCounter(0); > $counter2 = $counter1->add1(); > $counter3 = $counter2->add1(); > > var_dump([$counter1->value(), $counter2->value(), $counter3->value()]); > > $mutableCounter1 = new MutableCounter(0); > $mutableCounter2 = $mutableCounter1->add1(); > $mutableCounter3 = $mutableCounter2->add1(); > > var_dump([$mutableCounter1->value(), $mutableCounter2->value(), > $mutableCounter3->value()]); > ``` > > ( https://3v4l.org/IDhRY ) > > That's really really confusing, buggy, and, from a consumer PoV, broken > (LSP violation too, transitively). > As I think more about this, there's nothing about the current RFC in this code sample. What's breaking LSP here is the child class doing state modification, not PHP. To further expand that rationale, PHP allows us to create child classes. Whether that class will be LSP-safe or not is up to us, not up to PHP. However, the point still stands. Allowing child classes to break readonly will make it easier to build code that breaks LSP. The question then becomes: why is this being proposed and is it worth it? As I read through the RFC, the only reason this is being proposed is because "it breaks decoration via inheritance". Doesn't `final` cause the same issue? How is this problem being handled if the class is marked as final? If you can't extend a final class to build your "decoration via inheritance", why can't the same argument be applied to readonly classes? -- Marco Deleu