代码改变世界

变长参数处理

2017-10-31 11:52  brookin  阅读(183)  评论(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);