php - PHP 7+ 中的命名参数解决方案

标签 php parameter-passing php-7 named-parameters

如何在 PHP 7+ 中实现命名参数功能?

理想的语法是:

find($wildcard, relative = true, listIfEmpty = false) {
    ...
}

但是没有这样的解决方案。 在答案中,我实现了最短的解决方案,支持:

  • 重构
  • 输入参数和函数结果的提示
  • 可重复使用的参数集
  • 类型安全参数
  • 参数的默认值
  • 每个参数的 Getter(无硬编码字符串)
  • 非常简单的 setter/getter,您只需为每个参数更改一个名称

查看答案了解更多信息和实现

最佳答案

首先,在您的框架中或全局执行一次:

// the superclass that every params class will extend this
class params {
  protected function setter($key, $value) {
    if ($value === null) {
      return $this->{$key};
    }

    $this->{$key} = $value;
    return $this;
  }
}

然后,对每个需要具有专有名称的命名参数的函数执行此操作:

// define a helper method for simple instantiation
function params_find() { return new params_find(); }

// a params class that will use from find() method
class params_find extends params {

  // list of params with default values
  // below list is just a sample
  protected $listIfEmpty   = false;
  protected $structured    = true;
  protected $relative      = false;
  protected $prefix        = "";
  protected $justFileNames = false;

  // for each param duplicate line and just change function name exactly matching param name. setter/getter will done automatically
  function listIfEmpty($val = null)   { return $this->setter(__FUNCTION__, $val); }
  function structured($val = null)    { return $this->setter(__FUNCTION__, $val); }
  function relative($val = null)      { return $this->setter(__FUNCTION__, $val); }
  function prefix($val = null)        { return $this->setter(__FUNCTION__, $val); }
  function justFileNames($val = null) { return $this->setter(__FUNCTION__, $val); }
}

之后,使用此功能编写您的函数:

// your function that uses named arguments
// in this example $wildcard argument is required
function find($wildcard = [], params_find $opt = null) {
  if ($opt === null) {
    $opt = params_find();
  }

  // do something with your params like this
  if ($opt->structured()) {
    // ...
  }

  return $something_if_you_want;
}

最后,用最简单的界面来使用它:

// finally use your function with some params ( other params will have default values )
$files = find("*.css", params_find()
  ->structured(false)
  ->listIfEmpty(true)
  ->prefix("something")
);


// if you need all default values
$files = find("*.css");


// reusable options
$opt = params_find()
  ->listIfEmpty(false)
  ->prefix("something")
)
$files1 = find("*.css", $opt);
$files2 = find("*.html", $opt);
$files3 = find("*.scss", $opt
  ->structured(true)
);

关于php - PHP 7+ 中的命名参数解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56415163/

相关文章:

java - 将参数传递给Java中的方法

php - 警告 : Module ini file doesn't exist under/etc/php/7. 0/模组可用

PHP mail()/sendmail 自 Apache 2.4 PHP7 升级后无法正常工作

php - 在 while 循环中附加到数组是否安全?

php - 处理 JavaScript、PHP 和 MSSQL 中的反斜杠

javascript - 如何按值将对象传递给 nodejs/javascript 中的函数?

sql - 在单个参数中传递多个值

php - 将命令从 PHP 传递到 Python

php - SQL Server 的 ODBC 驱动程序 18]SSL 提供程序 : [error:1416F086]

php - 如果 while 循环返回空,则 ELSE 语句不返回