Table of Contents

PHP RFC: Readonly hooks

Introduction

Support for hooks on readonly properties was omitted from the original RFC, primarily to minimize complexity as there were questions around when it was safe to do. On further consideration, we believe that hooks on backed properties are sufficiently safe to support readonly, but not on virtual properties.

Proposal

We propose to allow both get and set hooks on readonly properties, if and only if it is a backed property.

Concerns to address

The main concern of allowing readonly hooks is that readonly, in theory, implies a property is immutable and idempotent. However, a get hook supports arbitrary code, so technically a developer could do something like:

class Unusual
{
    public readonly int $value { get => $this->value * random_int(1, 100); }
}

However, the same strange behavior could be implemented using __get:

class Test 
{
    public readonly int $test;
 
    public function __construct() 
    {
        unset($this->test);
    }
 
    public function __get($prop)
    {
        if ($prop === 'test') {
            return random_int(1, 100);
        }
    }
}
 
$t = new Test();
 
// These will print different numbers.
var_dump($t->test);
var_dump($t->test);

Additionally, if a readonly property is assigned a mutable object, that object may still be altered without violating the readonly rule. So even a readonly class is not really immutable to begin with.

That means the guarantee that readonly is idempotent is already not enforceable today, and in fact never has been. readonly is misleadingly named. It is really “write-once”, which is not the same as immutable (as shown above). But there's no reason that “write-once” need be incompatible with hooks.

Uses

ORMs and proxies

Despite the lack of a hard idempotency guarantee, there are valid uses for a readonly get hook, especially for ORMs and proxies. For example:

readonly class Product
{
    public function __construct(
        public string $name,
        public float $price,
        public Category $category,
    ) {}
}
 
// Generated code.
readonly class LazyProduct extends Product
{
   private DbConnection $dbApi;
 
   private string $categoryId;
 
   public Category $category {
       get {
           return $this->category ??= $this->dbApi->loadCategory($this->categoryId);
       }
   }
}

That is, we feel, an entirely reasonable use of hooks, and would allow for lazy-load behavior per-property on readonly classes.

This is subtly different from the Lazy Proxy RFC, which operates on the whole object at once. We believe both use cases are valuable and should be supported.

Inheritance

At present, the presence of even a single hook makes the class incompatible with marking the class readonly, even if it is, in practice, still readonly. Also, a readonly class may only be extended by a readonly class. That creates needless limitations.

readonly class Box
{
  public int $topLeft;
  public int $topRight;
  public int $bottomLeft;
  public int $bottomRight;
}
 
readonly class DerivedBox
{
  public int $area { get => $this->area ??= ($topRight - $topLeft * $bottomRight - $bottomLeft); }
}

There's no reason why this code should be invalid, but it is in 8.4. The only way around it would be to make both classes non-readonly, but then mark all four properties readonly manually.

Validation

A set hook, meanwhile, offers no issue for a backed readonly property. As long as it is backed we are able to determine if it is still uninitialized, and so a second set call would correctly fail as it should.

For example, one of the recommended uses of hooks is for property validation. Such validation would not in any way impede the readonly-ness of a backed property.

readonly class PositivePoint 
{
    public function __construct(
        public int $x { set => $value > 0 ? $value : throw new \Exception(); },
        public int $y { set => $value > 0 ? $value : throw new \Exception(); },
    ) {}
}

The above is not legal in 8.4, but it seems entirely safe to do for 8.5.

On balance, we believe the advantages and use cases for hooked readonly properties outweigh the potential for developers to do wonky things. For that reason, we propose to allow both get and set hooks on backed readonly properties.

Backward Incompatible Changes

None. No previously-valid code will become invalid. While it will be possible for a readonly property to return different values on subsequent calls, that is already the case as demonstrated above. So no guarantees are softened by this RFC.

Proposed PHP Version(s)

PHP 8.5

Rejected features

Implicit cache

An alternate approach that has been suggested is to make a readonly property with a get hook implicitly cache the value after the first call. That would essentially create a “lazy property” feature. However, there are two issues with that.

  1. It breaks the assumption that a get hook is always called.
  2. It would make it non-obvious that the hook is not virtual.

On the second point, consider:

class P {
  public string $first;
  public string $last;
  // Get hook only runs once.
  public readonly string $full { get => $this->first . $this->last; }
}

The code looks like $full should be a virtual property, since $this->full never appears in the hook body. But the readonly would make it implicitly backed. That makes determining when a property is virtual or backed even more involved, and is complexity we do not want to introduce.

A cached-on-first-call property is easy enough to do manually already, thanks to the null-assign operator:

readonly class P {
  public string $first;
  public string $last;
  // Get hook only runs once.
  public string $full { get => $this->full ??= $this->first . $this->last; }
}

And with this RFC becomes compatible with a readonly property.

init hooks

Another alternative proposal has been adding an init hook, which operates much like the implicit cache in the previous section but becomes explicitly labeled. While that is an interesting idea that has been floated a few times, it has enough complexities and edge cases of its own to address that we feel it is out of scope. However, this RFC is in no way incompatible with adding an init hook in the future should it be proposed.

Proposed Voting Choices

Yes or no vote. 2/3 required to pass.

Approve backed readonly hooks?
Real name Yes No
Final result: 0 0
This poll has been closed.

Patches and Tests

Link to the PR: https://github.com/php/php-src/pull/18757

Implementation

References