我目前有这种形式的类方法/函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我正在研究修改函数以使第一个参数可选,允许我只传递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];
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能指定我传递第一个参数作为参考?(我使用的是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;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,根据 的结果func_num_args(),解释每个参数的实际含义。
非常丑陋,而且会产生你以后不想维护的代码:)