Symfony: new object with classname from variable

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

id name
1 Administrator Admin
2 Redakteur Redakteur
3 Darf gar nichts Noob

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.