Jump to content

[SOLVED] Initiate class dynamically?


LemonInflux

Recommended Posts

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

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.