Other Types For A Property
<?php
class X {
public string $p {
set(string|A|null $value) {
$this->p = (string) $value;
}
get => $this-p . ' more';
}
}
class A {
function __toString() {
return 'abc';
}
}
$x = new X;
$x->p = new A;
It is possible to make a typed property accept more than its definition type.
Thanks to hooked property, the type of the incoming value may be different from the final type: indeed, the property hook has to convert that value to the actual type.
One constraint is that the supported type must be wider than the underlying property type. It is easily achieved by using a union type of the property type and all other needed types.
On the other hand, the get hook can only return its exact type: no covariance, no contravariance.
See Also
- A property’s writable type can now differ from its readable type
- Setting a value to a property [Try me]
PHP Features
Last updated: 10 September 2026