When Defining a constructor in a class I initially had something like:
public function __construct(MyClass $class){ ... }
However I wanted to be able to accept an array of MyClasses, how could you define this in your constructor?
Cheers
Not strictly typecasting, but will enforce what you're looking for.
public function __construct(array $classes){
foreach($classes as $inst){
if(!($inst instanceof ClassName)){
trigger_error('Array of objects passed to constructor must contain instances of ClassName', E_USER_ERROR);
}
//perform actions
}
}
You can only specify one type this way.
So, either an object, instance of MyClass :
public function __construct(MyClass $class){ ... }
Or an array :
public function __construct(array $data){ ... }
But you cannot specify your method only accepts an array of MyClass -- which means you'll have to check by yourself what kind of data are into the array your receive, in the second case.