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

时间:2019-06-02 12:43:20

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

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

理想的语法是:

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

但是没有解决方案可以做到这一点。 在答案中,我实现了支持以下内容的最短解决方案:

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

有关详细信息和实施方式,请参见答案

2 个答案:

答案 0 :(得分:1)

在您的框架中或全局进行:

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

答案 1 :(得分:1)

现在是PHP 8> =功能: https://wiki.php.net/rfc/named_params

<?php
// Using positional arguments:
array_fill(0, 100, 50);
 
// Using named arguments:
array_fill(start_index: 0, num: 100, value: 50);