Hi Ben,
> On 24. Feb 2026, at 01:45, Ben Ramsey <[email protected]> wrote:
>
> According to this RFC, both of these would be forbidden:
>
> readonly $a = new Foo();
> $b = $a;
As Tim already clarified, there is a common misconception about how PHP handles
objects internally. In PHP, objects are not passed by reference in the sense of
the `&` operator, but via an object identifier. This means that `$b = $a`
simply copies the object identifier, not a reference to the variable itself,
and is therefore perfectly valid:
```
<?php
readonly $a = new Foo();
$b = $a;
```
The readonly flag only prevents re-assignment of `$a` itself. The `&` operator,
on the other hand, would create a true reference to the variable `$a`, which
would allow `$a` to be modified indirectly through `$b`, effectively
circumventing the readonly flag. This is why taking a reference of a readonly
variable is forbidden.
I hope this clears up the concern.
> and:
>
> function modify(Foo $value): void {}
> readonly $a = new Foo();
> modify($a);
>
> I said "according to this RFC," but the RFC doesn't mention object behavior
> with readonly at all, which I think might be an oversight. The only place it
> hints at allowing objects is in the examples with `new PDO()`.
>
> Is the idea to allow objects (and arrays) similar to how JavaScript handles
> these with `const`? That is, the objects and arrays themselves are mutable,
> but the variable name cannot be reassigned to a new object or array?
Regarding your question about object and array behavior: you are correct that
the RFC did not explicitly document this, which was indeed an oversight on my
part.
As already mentioned above, the variable binding is immutable, meaning `$a`
cannot be reassigned to a different object, but the internal state of the
object can still be modified. This is also consistent with how the readonly
attribute behaves for class properties:
```
<?php
readonly $a = new Foo();
$a->value = "foo"; // Valid: modifying the object's internal state is allowed
$a = new Foo(); // Error: Cannot re-assign readonly variable
```
For arrays, however, the behavior differs from JavaScript. In PHP, arrays are
value types with copy-on-write semantics, not reference types. This means that
a readonly array is fully immutable, as neither the array itself nor its
elements can be modified after the initial assignment:
```
<?php
readonly $arr = [1, 2, 3];
$arr[] = 4; // Error: Cannot re-assign readonly variable
$arr[0] = 99; // Error: Cannot re-assign readonly variable
```
I have added explicit examples for both objects and arrays to the RFC to make
this behavior clear. I appreciate you flagging this.
(I apologize for the duplicate email, Ben. The first attempt was sent from an
incorrect address and did not go through properly.)
Cheers,
Joshua Rüsweg