Instantiating class by string using PHP 5.3 namespaces
Asked Answered
T

3

37

I can't get around an issue instantiating a new class by using a string variable and PHP 5.3. namespaces. For example, this works;

$class = 'Reflection';
$object = new $class();

However, this does not;

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

A fatal error gets thrown stating the class cannot be found. However it obviously can be instantiated if using the FQN i.e.;

$object = new \Application\Log\MyClass;

I've found this to be aparrent on PHP 5.3.2-1 but not not in later versions. Is there a work around for this?

Tirzah answered 21/2, 2011 at 23:10 Comment(0)
M
71
$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.

Munificent answered 21/2, 2011 at 23:13 Comment(1)
You can use also $class = __NAMESPACE__ . '\MyClass'; for namespacesLimonite
S
5

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"
Shanley answered 25/3, 2014 at 10:41 Comment(0)
B
0

I had the same problem and I have found some way around this problem. Probably not very efficient, but at least works.

function getController($controller)
{
    return new $controller;
}

$object = getController('Application\Log\MyClass');
Ballinger answered 20/3, 2020 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.