Dynamically creating objects using variable for class name

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wooshie
Forum Newbie
Posts: 5
Joined: Fri Jan 10, 2003 1:41 pm
Contact:

Dynamically creating objects using variable for class name

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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 ';
}
?>
wooshie
Forum Newbie
Posts: 5
Joined: Fri Jan 10, 2003 1:41 pm
Contact:

Post 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.
Post Reply