Hey Tim,
> On 10. Jul 2025, at 17:37, Tim Düsterhus <[email protected]> wrote:
>
> Hi
>
> Am 2025-07-08 17:10, schrieb Larry Garfield:
>> The only way to make the readonliness fully guaranteed would be to force a
>> readonly property to be cached
>
> Or by not allowing a `get` hook on readonly properties, of course.
>
> Best regards
> Tim Düsterhus
Personally, I would really like to have `get` hooks on readonly properties.
Please consider something like this:
```php
readonly class Foo
{
public function __construct(
public Output $style,
public string $some {
get => Output::One === $this->style ? ucfirst($this->some) :
strtoupper($this->some);
set => '' !== $value ? $value : throw new \Exception();
}
) {}
}
```
Easy-to-digest one-liners. Concerns remain separated. Set takes care of
validation, get formats.
If `get` would not be allowed, we couldn’t do such an obvious thing. For what
reason?
Instead we would need to delegate formatting to the `set` hook which is messy.
```php
readonly class Foo
{
public function __construct(
public Output $style,
public string $some {
set => '' !== $value ? (Output::One === $this->style ?
ucfirst($value) : strtoupper($value)) : throw new \Exception();
}
) {}
}
```
Now that I have proposed alternative implementations with caching, I don’t see
why `get` should not be allowed.
Cheers,
Nick
Aside: I added two links to alternative implementations to the PR description.