Symfony: new object with classname from variable

January 13, 2015 at 13:26

I had a superclass User, which was inherited by a few subclasses:
class Admin extends User { ... }
class Redakteur extends User { ... }
class Noob extends User { ... }
In my Controller I already know which class it's supposed to be. I did not want to do this via switch or if-query. The different types of users exist in a table with the columns id, name and, most importantly, classname: classname
3Darf gar nichtsNoob
To create the object using the classname, I use ReflectionClass:
        $tmp2 = new \ReflectionClass('Pack\UserBundle\Entity\\'.$group->getClassname());
        $user = $tmp2->newInstance($exists);
$user is now an instance of the $group entry.

Tags: reflectionclass variable klassennamen

Hinterlasse einen Kommentar: