Variables typées
<?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();
Une variable locale ne peut pas être typée.
C’est-à-dire qu’elle peut être typée au niveau de l’argument ou du retour, mais pas de façon permanente, comme une propriété.
Pour créer une variable typée, on peut utiliser une référence vers une propriété. La propriété peut être typée, et cette contrainte est étendue à la variable, avec un message dédié.
Cela fonctionne avec les propriétés statiques et normales. Et c’est un peu lourd à utiliser.
See Also
- Typed Variables [Try me]
PHP Error Messages
PHP Features
Last updated: 11 October 2026