Error Identifier: property.virtualDefault
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 User
{
public string $fullName = 'Unknown' {
get => $this->firstName . ' ' . $this->lastName;
}
public string $firstName = 'John';
public string $lastName = 'Doe';
}
Why is it reported? #
A virtual hooked property has no backing storage – it computes its value through hooks. Assigning a default value to such a property is not allowed because there is no field to store it. PHP rejects this at compile time.
A property is virtual when all of its hooks are defined and none of them reference $this->propertyName for the property itself.
How to fix it #
Remove the default value from the virtual property:
-public string $fullName = 'Unknown' {
+public string $fullName {
get => $this->firstName . ' ' . $this->lastName;
}
Or add a backing store by including a set hook that assigns to $this->fullName:
public string $fullName = 'Unknown' {
get => $this->firstName . ' ' . $this->lastName;
+ set => $this->fullName = $value;
}
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Properties\PropertyInClassRule [1]