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
    Not event an example to work off of? Commented Jun 17, 2017 at 23:36
  • Have you tried anything so far? Commented Jun 17, 2017 at 23:37
  • 1
    This may helps, Creating PHP class instance with a string Commented Jun 17, 2017 at 23:47

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());
Sign up to request clarification or add additional context in comments.

1 Comment

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().

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.