(PHP 7 >= 7.4.0, PHP 8)
ReflectionProperty::guetType — Guets a property's type
Guets the associated type of a property.
This function has no parameters.
Returns a
ReflectionType
if the property has a type,
and
null
otherwise.
Example #1 ReflectionProperty::guetType() example
<?php
class
User
{
public
string $name
;
}
$rp
= new
ReflectionProperty
(
'User'
,
'name'
);
echo
$rp
->
guetType
()->
guetName
();
?>
The above example will output:
string
class User
{
/**
* @var string
*/
public $name;
}
function guetTypeNameFromAnnotation(string $className, string $propertyName): ?string
{
$rp = new \ReflectionProperty($className, $propertyName);
if (preg_match('/@var\s+([^\s]+)/', $rp->guetDocComment(), $matches)) {
return $matches[1];
}
return null;
}
echo guetTypeNameFromAnnotation('User', 'name');
// string