Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic functions and type-hinting in PHP

Quick one:

Is there any way to enforce types for variadic functions in PHP? I'm assuming not, however maybe I've missed something.

As of now, I'm just forcing a single required argument of the needed type, and iterating to check the rest.

public function myFunction(MyClass $object){
    foreach(func_get_args() as $object){
        if(!($object instanceof MyClass)){
            // throw exception or something
        }
        $this->_objects[] = $object;
    }
}

Any better solutions?


Purpose:

A container object that acts as an iterated list of the child objects, with some utility functions. calling it with a variadic constructor would be something like this:

// returned directly from include
return new MyParent(
    new MyChild($params),
    new MyChild($params),
    new MyChild($params)
);

The other option could be an addChild method chain:

$parent = new MyParent;
return $parent
    ->addChild(new MyChild($params))
    ->addChild(new MyChild($params))
    ->addChild(new MyChild($params));

The children take several arguments to their constructor as well, so I'm trying to balance between legibility and processing expense.

like image 726
Dan Lugg Avatar asked Jun 10 '11 00:06

Dan Lugg


1 Answers

This is now possible with PHP 5.6.x, using the ... operator (also known as splat operator in some languages):

Example:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}
like image 190
jonathancardoso Avatar answered Nov 06 '22 08:11

jonathancardoso