Error Identifier: property.protected
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class Foo
{
protected string $bar = 'hello';
}
function doFoo(Foo $foo): void
{
echo $foo->bar;
}
Why is it reported? #
The property $bar is declared as protected, which means it can only be accessed from within the class itself or from its subclasses. Accessing it from outside the class hierarchy – such as from a standalone function or from an unrelated class – violates the visibility constraint and would cause a fatal error at runtime.
How to fix it #
Add a public getter method to expose the property value:
<?php declare(strict_types = 1);
class Foo
{
protected string $bar = 'hello';
+
+ public function getBar(): string
+ {
+ return $this->bar;
+ }
}
function doFoo(Foo $foo): void
{
- echo $foo->bar;
+ echo $foo->getBar();
}
Or change the property’s visibility to public if it is safe to do so:
<?php declare(strict_types = 1);
class Foo
{
- protected string $bar = 'hello';
+ public string $bar = 'hello';
}
Or move the accessing code into the class or a subclass where the protected property is accessible.
How to ignore this error #
You can use the identifier property.protected to ignore this error using a comment:
// @phpstan-ignore property.protected
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: property.protected