Instantiating class by string using PHP 5.3 namespaces

$class = 'Application\Log\MyClass';
$object = new $class();

The starting \ introduces a (fully qualified) namespaced identifier, but it's not part of the class name itself.


Another way to achieve the same result but with dynamic arguments is as follows. Please consider the class below as the class you want to instantiate.

<?php

// test.php

namespace Acme\Bundle\MyBundle;

class Test {
    public function __construct($arg1, $arg2) {
        var_dump(
            $arg1,
            $arg2
        );
    }
}

And then:

<?php

require_once('test.php');

(new ReflectionClass('Acme\Bundle\MyBundle\Test'))->newInstanceArgs(['one', 'two']);

If you are not using a recent version of PHP, please use the following code that replaces the last line of the example above:

$r = new ReflectionClass('Acme\Bundle\MyBundle\Test');
$r->newInstanceArgs(array('one', 'two'));

The code will produce the following output:

string(3) "one"
string(3) "two"