Instantiating a Namespaced PHP Class Dynamically
It’s pretty well known that you can instante a PHP class with a dynamic name using a variable:
$class = 'Foo_Bar';
$object = new $class();
is the same as
$object = new Foo_Bar();
It gets a little trickier if your class is defined in a namespace and you’re instantiating it from outside of that namespace. If you’re hard-coding a class, you need to use a leading backslash to reference the class.
namespace App;
$object = new \Foo\Bar();
// this would try to instantiate App\Foo\Bar
//$object = new Foo\Bar();
But if you’re using a dynamic name, the string should not have the leading backslash because the backslash is not part of the class name.
namespace App;
$class = 'Foo\Bar';
$object = new $class();
If you include the slash, your code won’t run on PHP 5.3.2 — you’ll get a Class '\\Foo\\Bar' not found
error. This stackoverflow post set me straight. As mentioned in the post, the code will work in PHP >= 5.3.3 with or without the slash.
Written by Jon Tai
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Related Tags
#php
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#