> Le 22 juil. 2025 à 09:43, Rob Landers <rob@bottled.codes> a écrit :
> 
> You can also implement this today, without using readonly:
> 
> class Foo {
>   public int $bar {
>     get => $this->bar;
>     set => empty($this->bar) ? $this->bar = $value : throw new 
> LogicException("nope");
>   }
> }
> 
> https://3v4l.org/2JagR#v8.4.10
> 

Your code is buggy, because `0` is “empty”:

https://3v4l.org/iUPvW#v8.4.10


> Should I be able to mark this class as readonly? I would think so.

I don’t think so.

If you want to *document* the intended invariant, you can put a @readonly tag 
in a phpdoc comment.

Adding a `readonly` keyword should *enforce* the invariant; the added value is 
that it would choke on bugs like the one you wrote just above, making it 
debugging much easier.


> The readonly keyword simplified that greatly, however, readonly has been 
> neutered compared to regular classes in the last couple of versions. There 
> are so many edge cases and non-implemented features with them -- mostly due 
> to this exact argument you are making -- that they're nearly worthless to 
> actually define immutable value objects in today's PHP.
> 

There are several issues with the readonly feature, mostly because of the 
“worse-is-better” philosophy. But we can slowly correct the main issues instead 
of making them worse.

—Claude


Reply via email to