【问题标题】:Conditional parameters in function definition PHP [closed]函数定义PHP中的条件参数[关闭]
【发布时间】:2014-12-19 22:47:30
【问题描述】:

我想知道,是否有可能为函数定义中的参数设置条件,例如:

function attachFile
(
  $function_method = "standard", // just default value..
  if ( $function_method == "standard" )
  {
    $next_parameter_for_classic_method,
    // ...
  }
  else if ( $function_method == "other_method" )
  {
    $next_parameter_for_other_method,
    // ...
  }
)
{
  // work...
}

这将大大简化函数的工作(至少我是这么认为的)。提前致谢。

【问题讨论】:

  • 你可以在函数头后面设置你的条件,如果有什么无效的,你可以返回false!
  • 使用数组作为参数。
  • @Downvoter 请留下一些评论,感谢其他人
  • 谁能告诉我,如果这个话题值得反对,为什么会如此糟糕?我知道,简单的点击很容易......显然对某些人来说很难解释-.-

标签: php function parameter-passing


【解决方案1】:

你可以传入一个默认值,否则你不能传入一个条件语句......你可以传入一个数组作为第二个参数,以便在需要时更容易......

function attachFile($function_method = "standard", $options = array())
{
  if ( $function_method == "standard" )
  {
    $next_parameter_for_classic_method = $options['next_parameter_for_classic_method '];
  }
  else if ( $function_method == "other_method" )
  {
    $next_parameter_for_other_method = $options['next_parameter_for_other_method'];
  }
}

示例语法:

attachFile('other_method', array('next_parameter_for_other_method'=>'someParameterValue'));

【讨论】:

  • 非常感谢!这正是我需要的☺
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
相关资源
最近更新 更多