确保在调用函数时不必定义所有变量


Make it so all variables don't have to be defined when a function is called

我使用000webhost,我做了一个自定义的PHP函数,看起来像这样:

function example($test1, $test2, $test3) {
   echo $test1 . $test2 . $test3;
}

然后我做example('hello');,它说:

PHP Error Message
Warning: Missing argument 2 for example(), called in /home/a8525001/public_html/test.php on line 5 and defined in /home/a8525001/public_html/test.php on line 2
Free Web Hosting
PHP Error Message
Warning: Missing argument 3 for example(), called in /home/a8525001/public_html/test.php on line 5 and defined in /home/a8525001/public_html/test.php on line 2
Free Web Hosting
1 

有没有办法我可以停止这些警告,而不访问服务器的php.ini?同样的代码在我的xampp服务器上运行良好…

提前感谢,

你有几个选择,这里有两个:

当设置为null(定义它们)时,可以使用以下命令:

function example($test = NULL, $test2 = NULL, test3 = NULL) {
    // use variables here but do something like this to check it isn't empty
    if($test !== NULL) {
        echo $test;
    }
    /// etc...and use the rest in whatever you need
}

或者您可以使用 func_get_args() ,它允许您这样做:

function example() {
    $args = func_get_args();
    foreach($args as $i => $arg) {
        echo "Argument {$i} is: {$arg} <br />";
    }
}

允许您执行如下操作:

example('derp', 'derp1', 'derp2');

上面的函数将返回:

Argument 0 is: derp
Argument 1 is: derp1
Argument 2 is: derp2

可选:您可以使用 func_num_args() 来确保函数中设置了参数。

刚刚得到答案:D,

要使函数中的变量成为可选的,可以在代码中定义它,如:

function example($test1, $test2 = NULL, $test3 = NULL) {
   echo $test1 . $test2 . $test3;
}

那么,这些值将已经被定义,但是当函数被调用时,如果可选值被定义,它将覆盖NULL。

来源:PHP函数缺少参数错误