如何在不传递可选参数的情况下将其设置为默认值? [英] How to set optional parameter to default without passing it?

查看:336
本文介绍了如何在不传递可选参数的情况下将其设置为默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不给函数调用任何值的情况下跳过第一个参数,以便第一个参数可以采用默认值NULL?

How can i skip first argument without giving any value in function call,so that first argument can take default value 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中的参数.

You cannot just skip an argument in PHP.

您可能希望考虑使用Perl技巧,并使用关联的数组.使用array_merge将参数与默认值合并.

You may wish to consider the Perl trick and use an associated array. Use array_merge to merge the parameters with the defaults.

例如

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));

这篇关于如何在不传递可选参数的情况下将其设置为默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆