instantiate a class from a variable in PHP? instantiate a class from a variable in PHP? php php

instantiate a class from a variable in PHP?


Put the classname into a variable first:

$classname=$var.'Class';$bar=new $classname("xyz");

This is often the sort of thing you'll see wrapped up in a Factory pattern.

See Namespaces and dynamic language features for further details.


If You Use Namespaces

In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.

MyClass.php

namespace com\company\lib;class MyClass {}

index.php

namespace com\company\lib;//Works fine$i = new MyClass();$cname = 'MyClass';//Errors//$i = new $cname;//Works fine$cname = "com\\company\\lib\\".$cname;$i = new $cname;


How to pass dynamic constructor parameters too

If you want to pass dynamic constructor parameters to the class, you can use this code:

$reflectionClass = new ReflectionClass($className);$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);

More information on dynamic classes and parameters

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

// The "..." is part of the language and indicates an argument array to unpack.$module = new $className(...$arrayOfConstructorParameters);

Thanks to DisgruntledGoat for pointing that out.