PHP - Get all parameters from a function (even the optional one)

前端 未结 2 850
醉话见心
醉话见心 2021-02-08 06:43

I want to get all parameters (passed or not) from a function.

Example:




        
相关标签:
2条回答
  • 2021-02-08 07:00

    func_get_args

    Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

    Ive created a function called func_get_all_args which takes advantage of Reflection. It returns the same array as func_get_args but includes any missing default values.

    function func_get_all_args($func, $func_get_args = array()){
    
        if((is_string($func) && function_exists($func)) || $func instanceof Closure){
            $ref = new ReflectionFunction($func);
        } else if(is_string($func) && !call_user_func_array('method_exists', explode('::', $func))){
            return $func_get_args;
        } else {
            $ref = new ReflectionMethod($func);
        }
        foreach ($ref->getParameters() as $key => $param) {
    
            if(!isset($func_get_args[ $key ]) && $param->isDefaultValueAvailable()){
                $func_get_args[ $key ] = $param->getDefaultValue();
            }
        }
        return $func_get_args;
    }
    

    Usage

    function my_function(){
    
        $all_args = func_get_all_args(__FUNCTION__, func_get_args());
        call_user_func_array(__FUNCTION__, $all_args);
    }
    
    public function my_method(){
    
        $all_args = func_get_all_args(__METHOD__, func_get_args());
        // or
        $all_args = func_get_all_args(array($this, __FUNCTION__), func_get_args());
    
        call_user_func_array(array($this, __FUNCTION__), $all_args);
    }
    

    This could probably do with a bit of improvement such ac catching and throwing errors.

    0 讨论(0)
  • 2021-02-08 07:10

    You can accomplish this using the ReflectionFunction function class.

    function foo($a, $b=1)
    {
        $arr = array();
        $ref = new ReflectionFunction(__FUNCTION__);
        foreach($ref->getParameters() as $parameter)
        {
            $name = $parameter->getName();
            $arr[$name] = ${$name};
        }
        print_r($arr);
    
        // ...
    }
    

    Calling the function:

    foo(1);
    

    Output:

    Array
    (
        [a] => 1
        [b] => 1
    )
    

    Demo

    0 讨论(0)
提交回复
热议问题