PHP 7+中的命名参数解决方案 [英] Named Parameters solution in PHP 7+

查看:410
本文介绍了PHP 7+中的命名参数解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I implement the named argument feature in PHP 7+?

理想的语法是:

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

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

But there is no solution to do like that. In the answer, I implemented the shortest possible solution that supports:

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

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

推荐答案

在您的Framework或全局中执行以下操作:

Do it one in your Framework or globally:

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

对每个需要使用专有名称命名参数的函数执行此操作:

Do it for each function that required named arguments with proper names:

// 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 it with the simplest interface:

// 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 7+中的命名参数解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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