在PHP5中使用func_get_args()通过引用传递变量



我现在有这样一个类方法/函数:

function set_option(&$content,$opt ,$key, $val){
   //...Some checking to ensure the necessary keys exist before the assignment goes here.
   $content['options'][$key][$opt] = $val;
}

现在,我正在考虑修改函数,使第一个参数成为可选的,允许我只传递3个参数。在这种情况下,使用一个类属性content来代替我省略的属性。

首先想到的是使用func_num_args() &Func_get_args()与此结合使用,例如:

function set_option(){
    $args = func_get_args();
    if(func_num_args() == 3){
        $this->set_option($this->content,$args[0],$args[1],$args[2]);
    }else{
       //...Some checking to ensure the necessary keys exist before the assignment goes here.
       $args[0]['options'][$args[1]][$args[2]] = $args[3];
   }
}

我如何指定我传递this的第一个参数作为引用?(我使用PHP5,所以指定变量通过函数调用的引用传递并不是我更好的选择之一。)

(我知道我可以修改参数列表,使最后一个参数是可选的,就像function set_option($opt,$key,$val,&$cont = false)一样,但我很好奇通过引用传递是否可以与上面的函数定义相结合。如果是,我宁愿用它

如果在函数声明中没有形参列表,就无法将实参用作引用。你需要做的是像

这样的东西
function set_option(&$p1, $p2, $p3, $p4=null){
    if(func_num_args() == 3){
        $this->set_option($this->content,$p1, $p2, $p3);
    }else{
        $p1['options'][$p2][$p3] = $p4;
    }
}

因此,根据func_num_args()的结果,解释每个参数的真正含义。

非常丑陋,并且使得你以后不想维护的代码:)

最新更新