0

I've got an array with some php class names (e.g. ClassOne.php)

classes = [ 'ClassOne' ,  'ClassTwo' ,  'ClassTree' ];

I want to write a loop that creates a new object for each of the class names. Without a loop, it looks like this:

$class1 = new ClassOne;
$class2 = new ClassTwo;
$class3 = new ClassTree;

After that object creation I want to check if $class1,2,3, ... is a instance of the main class (Components)

Is it possible to store the new objects in a array that can get iterated like this?

    $classes = [ $classs1, $class2, $class3 ];
    foreach($classes as $class)
    {
        if (is_object($class) && $class instanceof Component)
        {
             echo 'is an instance of Components';
        }
    }
3
  • So do these 3 classes actually exist? Like do you have a Class ClassOne {} etc Commented May 16, 2019 at 12:20
  • @RiggsFolly yes they allready exist. Now I want to proof if the class names in the array are instances of the class components Commented May 16, 2019 at 12:22
  • Tidied up the wording and code formating to improve readability. Commented May 17, 2019 at 21:16

1 Answer 1

2

You do simple loop as:

foreach($phpclasses as $class) {
    $classes[] = new $class();
}

Or you can cobine your loop and do:

foreach($phpclasses as $class) {
    $c = new $class();
    if (is_object($c) && $cinstanceof Component)
        echo 'is an instance of Components';
}

Can look at this question also

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your fast answer. I there a opportunity to do this also for classes with a constructor? So if something is needed to create a new object of a class
@phpprogrammerhelp312 Sure - see how it works with constructor here: 3v4l.org/stjco

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.