LemonInflux Posted May 4, 2008 Share Posted May 4, 2008 Here is my class: <?php class myClass { public $message; function __construct() { $this->message = "hi"; echo $this->message; } } ?> I have several classes similar to this, such as 'myClass2', 'yourClass', and 'testClass'. Is there a way to initiate these dynamically, as in: <?php $classes = array('myClass', 'myClass2', 'yourClass', 'testClass'); foreach($classes as $class) { $a = new //... What goes here? /* I can keep the same $a variable, because all of the class function is in the constructor, so as soon as the constructor is called (at the time of class initiation), the class has been used and there is no point keeping it open. But how do I initiate the class from an array item? Is it really as simple as '$a = new $class;'? */ } ?> Thanks in advance, Tom. Link to comment https://forums.phpfreaks.com/topic/104050-solved-initiate-class-dynamically/ Share on other sites More sharing options...
dooper3 Posted May 4, 2008 Share Posted May 4, 2008 No idea if that would work, but have you not tried it by putting $class after "new" in the foreach loop? Link to comment https://forums.phpfreaks.com/topic/104050-solved-initiate-class-dynamically/#findComment-532645 Share on other sites More sharing options...
LemonInflux Posted May 4, 2008 Author Share Posted May 4, 2008 I'm at school, it's a project. However, the school hasn't got any way to test it (XAMPP, etc) I shall test it when I get home, but I was just wondering if I could get an answer before I got home (so I could carry on working in this style) Link to comment https://forums.phpfreaks.com/topic/104050-solved-initiate-class-dynamically/#findComment-532646 Share on other sites More sharing options...
LemonInflux Posted May 4, 2008 Author Share Posted May 4, 2008 Found the answer on google. Yes, it works. Topic solved Link to comment https://forums.phpfreaks.com/topic/104050-solved-initiate-class-dynamically/#findComment-532666 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.