使用命名参数调用 PHP 函数
Python 很棒的一点是它能够使用名字将参数传递到一个函数,看起来是这样的:
my_foo_function(param_name="value", another_param_name="another value")
今天我想在 PHP 5.4 中做同样的事情(可轻松移植到 PHP 5.3),我写了一个 call_user_func_named 函数,类似 PHP 内置的 call_user_func_array 函数,代码如下:
<?php $x = function($bar, $foo="9") { echo $foo, $bar, "\n"; }; class MissingArgumentException extends Exception { } function call_user_func_named_array($method, $arr){ $ref = new ReflectionFunction($method); $params = []; foreach( $ref->getParameters() as $p ){ if( $p->isOptional() ){ if( isset($arr[$p->name]) ){ $params[] = $arr[$p->name]; }else{ $params[] = $p->getDefaultValue(); } }else if( isset($arr[$p->name]) ){ $params[] = $arr[$p->name]; }else{ throw new MissingArgumentException("Missing parameter $p->name"); } } return $ref->invokeArgs( $params ); } call_user_func_named_array($x, ['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss call_user_func_named_array($x, ['bar' => 'world']); //Only pass one parameter call_user_func_named_array($x, []); //Will throw exception
更新:很感谢一些热心的贡献者做的一些改进:
<?php $x = function($bar, $foo="9") { echo $foo, $bar, "\n"; }; class MissingArgumentException extends Exception { } function call_user_func_named_array($method, $arr){ $ref = new ReflectionFunction($method); $params = []; foreach( $ref->getParameters() as $p ){ if (!$p->isOptional() and !isset($arr[$p->name])) throw new MissingArgumentException("Missing parameter $p->name"); if (!isset($arr[$p->name])) $params[] = $p->getDefaultValue(); else $params[] = $arr[$p->name]; } return $ref->invokeArgs( $params ); } function make_named_array_function($func) { return function($arr) use ($func) { return call_user_func_named_array($func,$arr); }; } call_user_func_named_array($x, ['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss call_user_func_named_array($x, ['bar' => 'world']); //Only pass one parameter call_user_func_named_array($x, []); //Will throw exception $y = make_named_array_function($x); $y(['foo' => 'hello ', 'bar' => 'world']); //Pass all parameterss $y(['bar' => 'world']); //Only pass one parameter $y([]); //Will throw exception
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23