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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With