Variadic functions and type hints in PHP

Fast:

Is there a way to enforce types for variable functions in PHP? I suppose not, but maybe I missed something.

For now, I am simply forcing one required argument of the desired type and repeating 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 child objects, with some utility functions. calling it using the Variadic constructor would be something like this:

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

Another option might be a chain of methods addChild:

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

Children also take a few arguments into their constructor, so I try to balance intelligibility and processing costs.

+4
2

, , :) ( 1-n MyClass [ PHP 5.6, PHP 5.6+ . Variadic functions]), , ( ), , , .

. , , :

public function myFunction(MyClass $object, MyClass $object2=null, MyClass $object3=null, MyClass $object4=null, ...){
    foreach(func_get_args() as $object){
        if(null === $object){
            // throw exception or something
        }
        $this->_objects[] = $object;
    }
}

PHP , NULL, MyClass ( NULL, , , ). func_get_args(). , ( $object3), , func_get_args().

, , .

, . , , .


, , , , addMember:

class MyParent {
    private $children = array();
    public function __construct() {
        foreach(func_get_args() as $object) $this->addChild($object);
    }
    public function addChild(MyChild $object) {
        $this->children[] = $object;
    }
}

Collection.

:

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

PHP 5.6.x, ... ( splat ):

:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}
+14

All Articles