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.
Dynamically creating objects using variable for class name
Moderator: General Moderators
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 ';
}
?>