Creating a new class from a variable name in a namespace

Let's say for an instance I have a class:

//no namespace
class User { 
    //...
}

And I have a variable:

$model = 'User';

How to create an instance new Userwhen I am currently in the namespace?

new $modelworks when I'm not in the namespace. But what if I'm in a namespace and Usernot in a namespace.

Something like this does not work:

namespace Admin;

class Foo {
    function fighter($model)
    {
        return new \$model;
        // syntax error, unexpected '$model'
    }
}

}
+5
source share
1 answer

Put the full namespace in the variable first, and then use it.

<?php    
$namespace = '\\'.$model;

return new $namespace
?>

Same Topic: Can PHP namespaces contain variables?

+8
source

All Articles