php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Readonly properties mutable when assigning reference to them

Open ondrejmirtes opened this issue 4 years ago • 8 comments

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

ondrejmirtes avatar Jan 14 '22 10:01 ondrejmirtes

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.

pthreat avatar Jan 14 '22 10:01 pthreat

Not sure whether this is a bug; it might fall in the "readonly properties do not preclude interior mutability" category.

cmb69 avatar Jan 14 '22 11:01 cmb69

/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);

iluuu1994 avatar Jan 14 '22 11:01 iluuu1994

@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

ondrejmirtes avatar Jan 14 '22 11:01 ondrejmirtes

Yeah, this should not be allowed.

nikic avatar Jan 14 '22 11:01 nikic

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.

nikic avatar Jan 16 '22 09:01 nikic

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).

nikic avatar Jan 16 '22 09:01 nikic

Thank you @iluuu1994!

ondrejmirtes avatar Jul 01 '22 10:07 ondrejmirtes