(PHP 7 >= 7.4.0, PHP 8)
ReflectionProperty::getType — Récupère le type d'une propriété
Récupère le type associé à une propriété.
Cette fonction ne contient aucun paramètre.
Retourne une ReflectionType si la propriété a un type,
et null sinon.
Exemple #1 Exemple de ReflectionProperty::getType()
<?php
class User
{
public string $name;
}
$rp = new ReflectionProperty('User', 'name');
echo $rp->getType()->getName();
?>L'exemple ci-dessus va afficher :
string
class User
{
/**
* @var string
*/
public $name;
}
function getTypeNameFromAnnotation(string $className, string $propertyName): ?string
{
$rp = new \ReflectionProperty($className, $propertyName);
if (preg_match('/@var\s+([^\s]+)/', $rp->getDocComment(), $matches)) {
return $matches[1];
}
return null;
}
echo getTypeNameFromAnnotation('User', 'name');
// string