Beh*_*nam 5 php parameter-passing named-parameters php-7
如何在 PHP 7+ 中实现命名参数功能?
理想的语法是:
find($wildcard, relative = true, listIfEmpty = false) {
...
}
Run Code Online (Sandbox Code Playgroud)
但是没有这样的解决方案。在答案中,我实现了最短的解决方案,支持:
有关更多信息和实施,请参阅答案
首先,在您的框架中或全局执行一次:
// 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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,对每个需要具有正确名称的命名参数的函数执行此操作:
// 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); }
}
Run Code Online (Sandbox Code Playgroud)
之后,使用此功能编写您的函数:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
最后用最简单的接口来使用:
// 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)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1843 次 |
| 最近记录: |