PHP Function Argument to an array

后端 未结 4 441
时光说笑
时光说笑 2021-01-28 00:59

Can you do something crazy like this

function cool_function($pizza, $ice_cream) { 

   make the arguments in the array into an array 
   return $array_of_parama         


        
4条回答
  •  花落未央
    2021-01-28 01:27

    I'm not sure if you're looking for func_get_args which return all arguments passed to a function, or the ReflectionFunction class.

    A basic example of func_get_args:

    function cool_function($pizza, $ice_cream) { 
       return func_get_args();
    }
    

    But you don't need the arguments to make this work:

    function cool_function() { 
       return func_get_args();
    }
    // cool_function(1,2,3) will return array(1,2,3)
    

    The reflection option:

    /**
     * Returns an array of the names of this function
     */
    function getMyArgNames($a,$b,$c)
    {
        $args = array();
        $refFunc = new ReflectionFunction(__FUNCTION__);
        foreach( $refFunc->getParameters() as $param ){
             $args[] = $param->name;
        }
        return $args;
    }
    

    Or, for the really crazy:

    /**
     * Returns an associative array of the names of this function mapped 
     * to their values
     */
    function getMyArgNames($a,$b,$c)
    {
        $received = func_get_args();
        $i = 0;
        $args = array();
        $refFunc = new ReflectionFunction(__FUNCTION__);
        foreach( $refFunc->getParameters() as $param ){
             $args[$param->name] = $received[$i++];
        }
        // include all of those random, optional arguments.
        while($i < count($received)) $args[] = $received[$i++];
        return $args;
    }
    

提交回复
热议问题