PHP Function Argument to an array

后端 未结 4 482
时光说笑
时光说笑 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:11

    Actually, this is pretty easy (and read the manual: func_get_args — Returns an array containing a function's argument list, see as well: Variable-length argument lists):

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

    but as asked in comments, why do you need this?

    Or do you need the variable names? Reflection Docs is your friend:

    function cool_named($neutron, $electron)
    {
        $f = new ReflectionFunction(__FUNCTION__);
        $p = array();    
        foreach($f->getParameters() as $p1)
            $p[] = '$'.$p1->name;
    
        return $p;
    }
    
    var_dump(cool_named());
    

    Or just both? (Edit: taking under-length, optional and over-length parameters into account):

    function overall($neutron, $electron, $quark = 'xiaro')
    {
        $f = new ReflectionFunction(__FUNCTION__);
        $defined = $f->getParameters();
        $passed = func_get_args() + array_fill(0, count($defined), NULL);
    
        foreach($defined as &$param)
            $param = '$'.$param->name;
    
        return array_combine($defined + array_keys($passed), $passed);
    }
    
    var_dump(overall('clara', 'peter', 'moon', 'jupiter'));
    

提交回复
热议问题