class Expense {
/**
* @var int
*/
private $id;
}
我想使用反射获取类中变量的类型提示,因为默认值为null。
class Expense {
/**
* @var int
*/
private $id;
}
我想使用反射获取类中变量的类型提示,因为默认值为null。
尝试:
<?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"
尝试:
<?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"
获取完整的Docblock:
$reflection = new ReflectionProperty('Expense', 'id');
$doc = $reflection->getDocComment();
一点警告 - PHP加速器和一些库本身(即symfony核心)剥离注释,经常在 第二 跑。