我目前有一个这种形式的类方法/函数:
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];
}
}
我如何指定我将传递第一个参数作为引用? (我使用的是 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()
的结果,解释每个参数的真实含义。
非常丑陋,并且会生成您以后不想维护的代码:)
关于php - 在 PHP5 中使用 func_get_args() 通过引用传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7337098/