如何跳过第一个参数而不在函数调用中给出任何值,这样第一个参数可以取默认值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
Run Code Online (Sandbox Code Playgroud)
你不能只是跳过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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用函数
Test(array('otherparm' => 7));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2271 次 |
| 最近记录: |