douqi1931 2011-01-28 15:47
浏览 19
已采纳

PHP中嵌套的命名参数

Named parameters are great for a long list of options in a PHP user defined function or class. But what about nested options?

Eg:

function foobar($foo,$bar,$options=array()) {

    $default_options = array('option1'=>'','option2'=>'hello','option3'=>array('option1'=>true,'option2'=>''));

    $options = array_merge($default_options,(array)$options);
}

So option 3 is another array with suboptions. Would we need to put them in a for loop to merge the suboptions too? What would you guys do in this case?

EDIT:

This is the function call:

foobar('foo','bar',array('option1'=>'foo','option3'=>array('option1'=>false)));

Ending structure for $options:

array(
'option1'=>'foo',
'option2'=>'hello',
'option3'=>array(
    'option1'=>false,
    'option2'=>''
);
  • 写回答

4条回答 默认 最新

  • douluan5738 2011-01-28 16:00
    关注

    Why not just use the func_get_args function?

    function yourFunction($keys) {
        $default_options = array('test', array('test1' => array('test2')), 'test3');
        $options = func_get_args();
        array_shift($options);
    
        $options = array_combine($keys, $options); 
        $options = array_merge($default_options, $options);
    
        print_r($options);
    }
    
    // Usage
    yourFunction(array('option1', 'option2', 'option3', 'option4'), 'optionval1', array('optionval2-1', 'optionval2-2'), 'optionval3', 4);
    

    This way you have an array to start with and do not need to worry about anything else, and it can accept any number of parameters / arguments!

    EDIT:

    (Second edit, added the $keys as the first param) Modified the function above, here is the output. Not sure exactly what format of output you are looking for. So you may need to post the ending array structure you are after for your initial data given.

    Array
    (
        [0] => test
        [1] => Array
            (
                [test1] => Array
                    (
                        [0] => test2
                    )
    
            )
    
        [2] => test3
        [option1] => optionval1
        [option2] => Array
            (
                [0] => optionval2-1
                [1] => optionval2-2
            )
    
        [option3] => optionval3
        [option4] => 4
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了