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

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

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

Example:


         


        
2条回答
  •  执笔经年
    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

提交回复
热议问题