1

My question is what is a neat way to obtain an array of objects from an array of classes.

The array of classes I get by using array_filter() on get_declared_classes().

EDIT:

My own attempts were pretty correct, the thing was I forgot to return value of in_array() in callback function :

$classes_array = array_filter(
     get_declared_classes(),
        function($class_name){
           return in_array('IItem', class_implements($class_name));
         }

$objects_array;
    foreach($classes_array as $class){
        $objects_array[] = new $class();
    }
3

1 Answer 1

3

You can use array_map(), and refer to Creating PHP class instance with a string

$objects = array_map(function($v){
  return new $v();
}, get_declared_classes());
1
  • 1
    This answer is correct, thank you very much! But in fact it is analogous to my own attempts, so it pointed me to that something else is wrong with my code than instantiating object by new $class() as I thought before. It turned out that I just forgot to return the value of in_array(). Jun 18, 2017 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.