使用PHP的ReflectionClass。这可能吗?
我想得到一个方法列表和已定义的变量,如果可能的话,还要得到它们的默认值。
$reflection = new \ReflectionClass($var);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
print_r($methods); // only method names here :(
答案 0 :(得分:2)
使用ReflectionParameter::getDefaultValue()
方法。使用您的代码示例:
$reflection = new \ReflectionClass($var);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
$methodParameters = array();
foreach ($methods as $method) {
$parameters = $method->getParameters();
foreach ($parameters as $parameter) {
$name = $method->getName() . '::' . $parameter->getName();
$methodParameters[$name] = null;
if ($parameter->isOptional()) {
$methodParameters[$name] = $parameter->getDefaultValue();
}
}
}
一个例子:
class a {
public function methodOne() {
}
public function methodTwo($param) {
}
public function methodThree($param = 'foo') {
}
}
$var = new a();
$reflection = new \ReflectionClass($var);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
$methodParameters = array();
foreach ($methods as $method) {
$parameters = $method->getParameters();
foreach ($parameters as $parameter) {
$name = $method->getName() . '::' . $parameter->getName();
$methodParameters[$name] = null;
if ($parameter->isOptional()) {
$methodParameters[$name] = $parameter->getDefaultValue();
}
}
}
var_dump($methodParameters);
// results in this array:
array(2) {
["methodTwo::param"]=>
NULL
["methodThree::param"]=>
string(3) "foo"
}