变长参数处理
2017-10-31 11:52 brookin 阅读(185) 评论(0) 编辑 收藏 举报1. func_get_args
func_num_args();
func_get_args();
示例
function test() {
var_dump(func_num_args());
var_dump(func_get_args());
}
$params = array(
10,
'glop',
'test',
);
// invoke
call_user_func_array('test', $params);
2. using ... operator
Notice: PHP version > 5.6
meanwhile you can set the type of parameters
function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
foreach ( $intervals as $interval ) {
$dt->add( $interval );
}
return $dt;
}
// one
addDateIntervaslToDateTime( new DateTime, new DateInterval( 'P1D' ),
new DateInterval( 'P4D' ), new DateInterval( 'P10D' ) );
// two
$list = [new DateInterval( 'P1D' ), new DateInterval( 'P4D' ), new DateInterval( 'P10D' )];
addDateIntervaslToDateTime(new DateTime, ...$list);
In php 7
function do_something(int ...$all_the_others) { /**/ }
3. use ReflectionClass
$req = new Request();
$ps = [$req];
$ref = new \ReflectionClass(RequestCollection::class);
$o = $ref->newInstanceArgs($ps);
// same as follow
$o = new RequestCollection(...$ps);
作者:brookin
出处:http://www.cnblogs.com/brookin/
本文采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
出处:http://www.cnblogs.com/brookin/
本文采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。