Error Identifier: property.private
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 ParentClass
{
private string $secret = 'hidden';
}
class ChildClass extends ParentClass
{
public function getSecret(): string
{
return $this->secret; // ERROR: Access to private property $secret of parent class ParentClass.
}
}
Why is it reported? #
The code attempts to access a private property from outside the class where it is declared. Private properties are only accessible within the class that defines them – not from subclasses, not from parent classes, and not from outside code. Attempting to access a private property from a child class will result in accessing an undefined property rather than the parent’s private property.
How to fix it #
Change the property visibility to protected if it should be accessible by subclasses:
<?php declare(strict_types = 1);
class ParentClass
{
- private string $secret = 'hidden';
+ protected string $secret = 'hidden';
}
class ChildClass extends ParentClass
{
public function getSecret(): string
{
return $this->secret;
}
}
Or provide a getter method in the parent class:
<?php declare(strict_types = 1);
class ParentClass
{
private string $secret = 'hidden';
+
+ protected function getSecret(): string
+ {
+ return $this->secret;
+ }
}
class ChildClass extends ParentClass
{
public function getSecret(): string
{
- return $this->secret;
+ return parent::getSecret();
}
}
How to ignore this error #
You can use the identifier property.private to ignore this error using a comment:
// @phpstan-ignore property.private
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.private