Skip to content

Full Support of PHP 8.1 readonly property #6773

@simon-schubert

Description

@simon-schubert

Feature request

The rfc https://wiki.php.net/rfc/readonly_properties_v2 mentions:

Modifications are not necessarily plain assignments, all of the following will also result in an Error exception:

class Test {
    public function __construct(
        public readonly int $i = 0,
        public readonly [array](http://www.php.net/array) $ary = [],
    ) {}
}
 
$test = new Test;
$test->i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach ($test as &$prop);

I especially tested the following code:

<?php
final class Repository 
{ 
    /**
      * @param array<string, string> $data
      */
    public function __construct(private readonly array $data)
    {
    }
  
    public function remove(string $key): void
    {
     	unset($this->data[$key]);
    }
}

$repository = new Repository(['lorem' => 'ipsum', 'dolor' => 'sit']);
$repository->remove('lorem');

Which leads to:

No errors! 

see: https://phpstan.org/r/8e14a7a8-7663-49af-9885-21f44543cdfb

It would be amazing, if phpstan would support this!

Did PHPStan help you today? Did it make you happy in any way?

Indeed, it catches all the little things I did not consider. Every single day :)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions