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 Bar {}
class Foo
{
private Bar $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
public function check(): void
{
if (empty($this->bar)) {
echo 'empty';
}
}
}
Why is it reported? #
The property used inside empty() has a native type that is not nullable and PHPStan can determine the property has been initialized. Since the property is always assigned a value and cannot be null, empty() cannot be checking for an uninitialized or null state. In addition, the type is never falsy, so empty() is always false.
In the example above, $this->bar is typed as Bar and is always initialized in the constructor. An object value is never falsy, so empty() on it is redundant.
How to fix it #
Remove the redundant empty() check since the property is always initialized and never falsy:
<?php declare(strict_types = 1);
class Foo
{
private Bar $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
public function check(): void
{
- if (empty($this->bar)) {
- echo 'empty';
- }
+ echo $this->bar::class;
}
}
How to ignore this error #
You can use the identifier empty.initializedProperty to ignore this error using a comment:
// @phpstan-ignore empty.initializedProperty
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: empty.initializedProperty