Readonly properties mutable when assigning reference to them
Description
Readonly properties should not be mutable with any means, but the following code surprisingly works (https://3v4l.org/qiDTk):
<?php
class Foo
{
public readonly int $bar;
public function set(int &$i)
{
$this->bar = &$i;
}
}
$i = 1;
$foo = new Foo();
$foo->set($i);
$i = 20;
var_dump($foo->bar); // 20
Additionally, without the & in int &$i, the property value stays 1 but does not report any error: https://3v4l.org/NMDAp
PHP Version
PHP 8.1
Operating System
No response
However one must note that the following example works as intended:
<?php // lint >= 8.1
namespace ReadonlyPropertyPassedByRef;
class Foo
{
public readonly int $bar;
public function set(int &$i)
{
$this->bar = &$i;
}
}
$i = 1;
$z = 25;
$foo = new Foo();
$foo->set($i);
$i = &$z;
var_dump($foo->bar);
The reference of the variable has been set as read only, not it's value.
Not sure whether this is a bug; it might fall in the "readonly properties do not preclude interior mutability" category.
/cc @nikic
The engine does prevent creating references from readonly properties.
https://3v4l.org/cRgNM#v8.1.1
Maybe we could do the same in the other direction. https://3v4l.org/M1n37#v8.1.1
class Foo {
public readonly int $bar;
public function __construct(int &$bar) {
// Error right here, can't assign reference
$this->bar = &$bar;
}
}
$i = 42;
$foo = new Foo($i);
$i++;
var_dump($foo->bar);
@cmb69 I’d consider it a bug because otherwise this sentence from the RFC isn’t really true:
Reading a readonly property will always return the same value, no matter what code runs in between
Yeah, this should not be allowed.
In zend_std_get_property_ptr_ptr(), we currently allow acquiring a property pointer if the current value is undef and the scope has initialization access. This then allows zend_assign_to_property_reference() to assign a reference to the property.
Always falling back to read_property for readonly props means that $obj->prop[] = 1 no longer works as an initializing assignment (it will generate a "must not be accessed before initialization" error). That's probably not a big loss, as the sane way to write that would be $obj->prop = [1] (you can only do the append once). The error message for the $obj->prop =& $ref case is also not great (same "accessed before initialization" error).
Thank you @iluuu1994!