如何在 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/