Error Identifier: method.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 function doSomething(): void
{
echo 'hello';
}
}
function doFoo(Foo $foo): void
{
$foo->doSomething(); // ERROR: Call to protected method doSomething() of class Foo.
}
Why is it reported? #
The code attempts to call a protected method from a context where it is not accessible. In PHP, protected methods can only be called from within the class that defines them or from a subclass. Calling a protected method from outside the class hierarchy is a language-level error.
How to fix it #
If the method should be accessible from outside the class, change its visibility to public:
<?php declare(strict_types = 1);
class Foo
{
- protected function doSomething(): void
+ public function doSomething(): void
{
echo 'hello';
}
}
If the method should remain protected, call it from within the class or a subclass:
<?php declare(strict_types = 1);
class Foo
{
protected function doSomething(): void
{
echo 'hello';
}
+ public function run(): void
+ {
+ $this->doSomething();
+ }
}
function doFoo(Foo $foo): void
{
- $foo->doSomething();
+ $foo->run();
}
How to ignore this error #
You can use the identifier method.protected to ignore this error using a comment:
// @phpstan-ignore method.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: method.protected