Skip to content

ReflectionProperty::isProtectedSet() not working as expected #19128

@damek24

Description

@damek24

Description

The following code:

<?php
class TestClass
{
    public function __construct(
        public private(set) int $a,
        public protected(set) int $b,
        public readonly int $c,
    )
    {
    }
}
class Test2Class extends TestClass
{
    public function setProp(int $x)
    {
        $this->c = $x;
    }
}
$r = new \ReflectionClass(\TestClass::class);
$properties = $r->getProperties();
$x = array_map(fn($prop) => ['private_set' => $prop->isPrivateSet(), 'protected_set' => $prop->isProtectedSet()], $properties);
print_r($x);
$y = new \Test2Class(1,2,3);
$y->setProp(5);

Resulted in this output:

[
    [
      "private_set" => true,
      "protected_set" => false,
    ],
    [
      "private_set" => false,
      "protected_set" => true,
    ],
    [
      "private_set" => false,
      "protected_set" => true,
    ],
  ]

Error: Cannot modify readonly property \TestClass::$c.

As I did not find this case in the documentation, I am not sure what is the correct behaviour, but I would expect one of two options for the readonly property:

1st option: A readonly property should not be considered as protected(set):

    [
      "private_set" => false,
      "protected_set" => false,
    ],

for readonly property $c

2nd option: If a readonly property is considered protected(set), then the property should be modifiable in subclasses (but it is not):

No error should be thrown during the following method call:
$y->setProp(5); // Currently throws: Error: Cannot modify readonly property

PHP Version

PHP 8.4.10 (cli) (built: Jul  3 2025 12:41:53) (NTS)
Copyright (c) The PHP Group
Built by Debian
Zend Engine v4.4.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.4.10, Copyright (c), by Zend Technologies

Operating System

No response

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