函数中的多个可选参数

4

getAllForms($data=null)

getAllForms() and getAllForms("data")

这将有效。但我想在函数中添加两个可选参数,如下所示:
getAllForms($arg1=null,$arg2=null)

getAllForms() and getAllForms("data")

我该如何实现这个目标?


如果您想要有多个“数据”参数,请使用数组。否则,将它们命名为“$data1”和“$data2”。 - Daan Timmer
是的,Daan,我正在使用数组,data1和data2都是数组。问题是我只能设置一个参数为可选(null)。 - sudeep cv
5个回答

11

你可以尝试:

function getAllForms() {
    extract(func_get_args(), EXTR_PREFIX_ALL, "data");
}

getAllForms();
getAllForms("a"); // $data_0 = a
getAllForms("a", "b"); // $data_0 = a $data_1 = b
getAllForms(null, null, "c"); // $data_0 = null $data_1 = null, $data_2 = c

6
你也可以尝试使用func_get_arg函数,它可以将n个参数传递给一个函数。 http://php.net/manual/zh/function.func-get-args.php 示例
function foo(){
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);

3

试试这个:

getAllForms($data=null,$data2=null)

你需要以这种模式调用它:

getAllForms()
getAllForms("data")
getAllForms("data","data2")

第二个参数必须与第一个参数的名称不同。

1

你已经描述了如何做到这一点:

function getAllForms($arg1 = null, $arg2 = null)

除了第二个变量名必须不同之外,每个变量名都必须不同。


1
<? php
function getAllForms($data1 = null, $data2 = null)
{
    if ($data1 != null)
    {
        // do something with $data1
    }

    if ($data2 != null)
    {
        // do something with $data2
    }
}
?>

getAllForms();
getAllForms("a");
getAllForms(null, "b");
getAllForms("a", "b");

或者

<? php
function getAllForms($data = null)
{
    if (is_array($data))
    {
        foreach($data as $item)
        {
            getAllForms($item);
        }
    }
    else
    {
        if ($data != null)
        {
            // do something with data.
        }
    }
}

getAllForms();
getAllForms("a");
getAllForms(array("a"));
getAllForms(array("a", "b"));
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接