欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-12 15:21:38
...

有时候我们需要获取函数需要传入的参数,可以利用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);

结果如下:

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

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>";

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

参考:

http://www.php.net/manual/zh/book.reflection.php