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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值