Typed Variables¶
<?php
class X {
public static int $int = 1;
public string $string = 'abc';
}
function foo() {
$foo = new X();
$varString = &$foo->string;
$varString = [];
//Cannot assign array to reference held by property X::$string of type string
$varInt = &X::$int;
$varInt = 'abc';
//Cannot assign string to reference held by property X::$int of type int
}
foo();
A local variable cannot be typed.
I mean, it may be typed at argument or return time, but not permanently, like a property.
To create a typed variable, one may use a reference to a property. The property may be typed, and this constraint is extended to the variable, with a dedicated message.
It works on static and normal properties. And it looks a bit cumbersome to use.
See Also¶
Typed Variables [Try me]
PHP Error Messages¶
PHP Features¶
Last updated: 14 July 2026