Page 1 of 1

Dynamically creating objects using variable for class name

Posted: Wed Jan 22, 2003 10:34 am
by wooshie
I'm eager to know if the subj is possible.
I got such situation like:
1) Several classes, more coming, they serve similiar purposes but each have specific functionality
2) I'm getting list of objects needed from table
3) I need to create the class object, class name is stored in variable (got from DB).

What I've done - got the class name, included corresponding file (no problem with that), tried such construction like:

/************************************/
$obj = new $className;
/************************************/

and got the error:
Fatal error: Cannot instantiate non-existent class

However I've included the file containing the class

Would be very nice to see any solution for this problem.

Posted: Wed Jan 22, 2003 12:12 pm
by volka
tested this and it worked as expected

Code: Select all

<?php   
class ClassA
{
	function name()
	{
		return 'this is class A';
	}
}

class ClassB
{
	function name()
	{
		return 'this is class B';
	}
}

$classes = array('ClassA', 'ClassB', 'ClassC');
foreach($classes as $cname)
{
	if (class_exists($cname))
	{
		$o = new $cname;
		echo $o->name(), ' ';
	}
	else
		echo $cname, ' undefined ';
}
?>

Posted: Wed Jan 22, 2003 1:17 pm
by wooshie
thanks a lot, i got it working too, it didn't work because of my conflict with logic. It will kill me one day.