退房 PHP 5.4
他们计划今年推出PHP 5.4,它将具有参数>getHint()的反射方法(当前在开发版本中)。
但是,在5.4正式发布之前,我正在使用Reflectleclass::getDocComment()
例如,可以在@param中指定它。
// Adapted from meager's example
class Bar {}
class Foo {
/**
* @param MyType $value
* @param array $value2
*/
function __construct(Bar $value, array $value2) {
}
}
// Regex
function getHint( $docComment, $varName ) {
$matches = array();
$count = preg_match_all('/@param[\t\s]*(?P<type>[^\t\s]*)[\t\s]*\$(?P<name>[^\t\s]*)/sim', $docComment, $matches);
if( $count>0 ) {
foreach( $matches['name'] as $n=>$name ) {
if( $name == $varName ) {
return $matches['type'][$n];
}
}
}
return null;
}
$reflection = new ReflectionClass('Foo');
$constructor= $reflection->getConstructor();
$docComment = $constructor->getDocComment();
$params = $constructor->getParameters();
foreach ($params AS $param) {
$name = $param->getName();
echo $name ." is ";
//echo $param->getHint()."\n"; // in PHP 5.4
echo getHint($docComment, $name)."\n"; // work around
}
输出:
value is MyType
value2 is array