Error Identifier: property.uninitialized
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
{
private string $name;
public function getName(): string
{
return $this->name;
}
}
Why is it reported? #
The class has a typed property that is never assigned a value – neither as a default value nor in the constructor. Accessing an uninitialized typed property in PHP causes a fatal error (Typed property must not be accessed before initialization).
This rule does not apply to readonly properties, which have their own dedicated checks.
How to fix it #
Assign a default value to the property:
class Foo
{
- private string $name;
+ private string $name = '';
}
Or initialize the property in the constructor:
class Foo
{
private string $name;
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
public function getName(): string
{
return $this->name;
}
}
How to ignore this error #
You can use the identifier property.uninitialized to ignore this error using a comment:
// @phpstan-ignore property.uninitialized
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.uninitialized