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


class Expense {

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

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


1369
2018-06-06 09:46


起源



答案:


尝试:

<?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);
    }
}

产量

string(3) "int"

12
2018-06-06 09:51



简单的代码 - user1502826


答案:


尝试:

<?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);
    }
}

产量

string(3) "int"

12
2018-06-06 09:51



简单的代码 - user1502826


获取完整的Docblock:

$reflection = new ReflectionProperty('Expense', 'id');

$doc = $reflection->getDocComment();

2
2018-06-06 09:51





一点警告 - PHP加速器和一些库本身(即symfony核心)剥离注释,经常在 第二 跑。


0
2018-06-06 10:44