我已经写了一个PHP函数,可以接受10个参数,但只需要2个参数。有时,我想定义第八个参数,但在到达第八个参数之前,我不想为每个参数键入空字符串。
我的一个想法是传递一个带有参数数组的抽象函数,该数组将其传递给实际函数。
有没有更好的方法来设置函数,这样我就可以只传递我想要的参数了?
发布于 2010-10-20 22:33:22
在本例中,我所做的是传递一个数组,其中键是参数名,值是值。
$optional = array(
"param" => $param1,
"param2" => $param2
);
function func($required, $requiredTwo, $optional) {
if(isset($optional["param2"])) {
doWork();
}
}
发布于 2010-10-20 23:21:56
要实现您想要的功能,可以使用数组Like Rabbot said (不过,如果过度使用,这可能会成为文档记录/维护的一项痛苦)。或者只使用传统的可选参数。
//My function with tons of optional params
function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
{
//Do stuff
}
my_func('Hi', 'World', null, null, 'Red');
然而,我通常会发现,当我开始编写一个带有那么多参数的函数/方法时--通常情况下,它是一种代码气味,可以被重构/抽象成更干净的东西。
//Specialization of my_func - assuming my_func itself cannot be refactored
function my_color_func($reg_a, $reg_b, $opt = 'Red')
{
return my_func($reg_a, $reg_b, null, null, $opt);
}
my_color_func('Hi', 'World');
my_color_func('Hello', 'Universe', 'Green');
发布于 2018-05-01 02:53:21
您可以将缺省值设置为null。
<?php
function functionName($value, $value2 = null) {
// do stuff
}
https://stackoverflow.com/questions/3978929
复制相似问题