php:使用反射获取变量类型提示

yel*_*lo3 13 php reflection types class

class Expense {

    /**
     * @var int
     */
    private $id;
}
Run Code Online (Sandbox Code Playgroud)

我想使用反射获取类中变量的类型提示,因为默认值为null.

Yos*_*shi 16

尝试:

<?php
class Expense {

    /**
     * @var int
     */
    private $id;
}

$refClass = new ReflectionClass('Expense');
foreach ($refClass->getProperties() as $refProperty) {
    if (preg_match('/@var\s+([^\s]+)/', $refProperty->getDocComment(), $matches)) {
        list(, $type) = $matches;
        var_dump($type);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

string(3) "int"
Run Code Online (Sandbox Code Playgroud)


IMB*_*IMB 5

对于 PHP 7.4

$reflection = new \ReflectionProperty('className', 'propertyName');
echo $reflection->getType()->getName();
Run Code Online (Sandbox Code Playgroud)