Type of parameter $%s of hook %s::$%s::set must be compatible with property type¶
Description¶
When a set hook declares an explicit parameter type, that type is what callers of $object->prop = $value are constrained to. Because the hook is the only way to write to the property, its parameter type must be able to accept every value that the property’s own declared type allows; it must be the same as, or wider (contravariant) than, the property type, never narrower.
In the example, $prop is declared as string|array, but the set hook only accepts string. An assignment of an array would satisfy the property’s declared type but be rejected by the hook’s parameter type, which PHP considers an incompatible, and therefore invalid, declaration.
The same error occurs when the property itself has no explicit type (implicitly mixed) but the set hook restricts its parameter to a specific type, since mixed is wider than any concrete type.
Example¶
<?php
class Test {
public string|array $prop {
set(string $prop) {}
}
}
?>
Literal Examples¶
Type of parameter $prop of hook Test::$prop::set must be compatible with property type
Solutions¶
Widen the
sethook’s parameter type so that it accepts everything the property’s declared type allows, e.g. changeset(string $prop)toset(string|array $prop).Remove the explicit type from the
sethook’s parameter, letting it default to the property’s type.Narrow the property’s declared type to match what the
sethook is willing to accept.
Changed Behavior¶
This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.