【问题标题】:PHP listing function arguments with initial valuesPHP 列出具有初始值的函数参数
【发布时间】:2013-07-22 00:07:35
【问题描述】:

所以我知道,如果在这样调用函数时未提供默认值,您可以将函数的参数编码为具有默认值:

我添加了一个如何实现接口的示例:

interface my_interface {

  function my_function();

}

class my_class implements my_interface {

  # because the interface calls for a function with no options an error would occur
  function my_function($arg_one, $arg_two = 'name') {
    ...
  }

}


class another_class implements my_interface {

  # this class would have no errors and complies to the implemented interface
  # it also can have any number of arguments passed to it
  function my_function() {

    list($arg_one, $arg_two, $arg_three) = func_get_args();

    ...

  }

}

但是,我喜欢让我的函数调用func_get_args() 方法,这样当在类中使用它们时,我可以从接口实现函数。有没有办法使用 list() 函数,以便我可以为变量分配默认值,或者我需要以冗长而丑陋的方式来做吗?我现在拥有的是:

function my_function() {

  list($arg_one, $arg_two) = func_get_args();
  if(is_null($arg_two)) $arg_two = 'name';

  ...

}

我想要的是完成同样的事情,但不是那么冗长的东西。也许是这样,但当然不会标记错误:

function my_function() {

  # If $arg_two is not supplied would its default value remain unchanged?
  # Thus, would calling the next commented line would be my solution?
  # $arg_two = 'name';
  list($arg_one, $arg_two = 'name') = func_get_args();

  ...

}

【问题讨论】:

  • 我不知道你为什么要这样做,是什么意思,“以便在类中使用它们时我可以从接口实现函数?”。你能说明为什么这很重要吗?
  • 我进行了编辑以更好地理解@elclanrs

标签: php list function arguments


【解决方案1】:

您不能在 list 语言结构中使用默认值。但是,您可以使用自 PHP 5.3 起提供的修改后的三元运算符:

function my_function() {
  $arg_one = func_get_arg(0) ?: 'default_one';
  $arg_two = func_get_arg(1) ?: 'name';
  // ...
}

但是,请注意隐式类型转换。在我的示例中,my_function(0, array()) 的行为与 my_function('default_one', 'name') 相同。

【讨论】:

  • 哦,这很聪明,看起来不错。可惜我不能修改列表功能。
猜你喜欢
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2019-02-25
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多