您的位置:首页 > 编程语言 > PHP开发

php获取函数参数,获取类里面的方法名

2017-05-25 12:23 856 查看

有时候我们需要获取函数需要传入的参数,可以利用php的反射函数获取,或者类里面的所有公开的方法。

1、获取函数参数名称:

function getFucntionParameterName($func) {
$ReflectionFunc = new \ReflectionFunction($func);
$depend = array();
foreach ($ReflectionFunc->getParameters() as $value) {
$depend[] = $value->name;
}
return $depend;
}

function test($a, $c, $b, $d = 20) {

}

$paramName = getFucntionParameterName('test');

print_r($paramName);


结果如下:



2、获取类里面的所有公共方法名:

<?php

class GetNames {
/**
* 获取一个函数的依赖
* @param  string|callable $func
* @param  array  $param 调用方法时所需参数 形参名就是key值
* @return array  返回方法调用所需依赖
*/
function getFucntionParameter($func, $param = []) {
if (!is_array($param)) {
$param = [$param];
}
$ReflectionFunc = new \ReflectionFunction($func);
$depend = array();
foreach ($ReflectionFunc->getParameters() as $value) {
if (isset($param[$value->name])) {
$depend[] = $param[$value->name];
} elseif ($value->isDefaultValueAvailable()) {
$depend[] = $value->getDefaultValue();
} else {
$tmp = $value->getClass();
if (is_null($tmp)) {
throw new \Exception("Function parameters can not be getClass {$class}");
}
$depend[] = $this->get($tmp->getName());
}
}
return $depend;
}

//获取方法里面的参数名
function getFucntionParameterName($func) {
$ReflectionFunc = new \ReflectionFunction($func);
$names = array();
foreach ($ReflectionFunc->getParameters() as $value) {
$names[] = $value->name;
}
return $names;
}

private function _test($a, $c, $b, $d = 20) {

}
}

function test1($a, $b, $c) {

}

$new = new GetNames();
$names = $new->getFucntionParameterName('test1');
$methords = get_class_methods('GetNames');
echo "<pre>";
print_r($names);
print_r($methords);
echo "</pre>";




参考:

http://www.php.net/manual/zh/book.reflection.php
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 php