Error Identifier: unset.hookedProperty
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 $name {
set(string $value) {
$this->name = trim($value);
}
}
public function reset(): void
{
unset($this->name);
}
}
Why is it reported? #
PHP 8.4 introduced property hooks. A property with hooks cannot be unset because PHP does not support unset() on hooked properties. Attempting to do so results in a fatal error at runtime.
In the example above, the $name property has a set hook, making it a hooked property. Calling unset($this->name) on it is not allowed.
How to fix it #
Instead of unsetting the property, assign a default or empty value:
<?php declare(strict_types = 1);
class User
{
public string $name {
set(string $value) {
$this->name = trim($value);
}
}
public function reset(): void
{
- unset($this->name);
+ $this->name = '';
}
}
If the property should support being absent, consider making it nullable and assigning null:
<?php declare(strict_types = 1);
class User
{
- public string $name {
- set(string $value) {
+ public ?string $name {
+ set(?string $value) {
$this->name = trim($value);
}
}
public function reset(): void
{
- unset($this->name);
+ $this->name = null;
}
}
How to ignore this error #
You can use the identifier unset.hookedProperty to ignore this error using a comment:
// @phpstan-ignore unset.hookedProperty
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: unset.hookedProperty
Rules that report this error #
- PHPStan\Rules\Variables\UnsetRule [1]