如何在函数调用中跳过第一个参数而不给定任何值,以便第一个参数可以取默认值NULL?
function test($a = NULL, $b = true){
if( $a == NULL){
if($b == true){
echo 'a = NULL, b = true';
}
else{
echo ' a = NULL, b = false';
}
}
else{
if($b == true){
echo 'a != NULL, b = true';
}
else{
echo ' a!=NULL, b = false';
}
}
}
test(); //ok
test(NULL); //ok
test(5); //ok
test(5,false) //ok
test(,false); // How to skip first argument without passing any value? ->PARSE error
// i don' want to use default value for first argument, although test(NULL,false)
// or test('',false) will work but can i skip first argument somehow?
// i want to pass only second argument, so that first arg will be default set by
// function
在PHP中不能跳过一个参数。
您可能希望考虑Perl技巧并使用关联的数组。使用array_merge
将参数与默认值合并。
例如
function Test($parameters = null)
{
$defaults = array('color' => 'red', 'otherparm' => 5);
if ($parameters == null)
{
$parameters = $defaults;
}
else
{
$parameters = array_merge($defaults, $parameters);
}
}
然后调用类似的函数
Test(array('otherparm' => 7));
您可以更改参数的位置,也可以将参数作为数组传递,例如:
test($options);
将您的函数重新定义为
function test($b = true,$a = NULL){
//logic here
}
你可以称之为测试(5);避免第二个参数。
YOu必须使用PHP函数标准定义的格式
test("",false);
您的需求适用于jquery库。。。用于传递其函数的参数。但不在PHP 中