假设这是我提到的代码的一个示例。
<?php
function my_function($argument_1, $argument_2){
echo $argument_1.' '.$argument_2;
}
my_function('This is argument_1');
?>
问题是,如果我只使用1个参数调用它,my_function
仍然像上面的代码一样提供吗?
注:我已经在我的localhost (XAMPP)上尝试过了,它正常运行,没有定义变量错误(仍然打印出$argument_1
),但我想知道这是一般情况还是因为我的php配置在我的localhost
Thanks in Advance
如果在定义中为第二个参数定义了默认值,则可以只使用一个参数调用它,例如:
function my_function($argument_1, $argument_2=''){
echo $argument_1.' '.$argument_2;
}
my_function('This is argument_1');
如果没有提供第二个参数,它将以空字符串作为第二个参数,并且不会抛出任何警告。
否则会看到:
警告:my_function()
缺少参数2
:
注意:未定义变量:argument_2
和第二个参数仍然作为空字符串。
另一方面,您可以使用比定义中更多的参数调用函数,并通过func_get_args()
函数检索它们,例如:
function my_function(){
echo implode(' ', func_get_args());
}
my_function('This is argument_1', 'This is argument_2');
输出:This is argument_1 This is argument_2
检查函数调用
call_user_func_array("my_function", array("one", "two"));
call_user_func_array("my_function", array("one"));
call_user_func_array("my_function");
原因:http://php.net/manual/en/functions.arguments.php