6

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

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

And I have a variable:

$model = 'User';

How do I instantiate a new User when I am currently in a namespace?

new $model works when I'm not in a namespace. But what if I am in a namespace and User is not in a namespace.

Something like this doesn't work:

namespace Admin;

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

}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
Jürgen Paul
  • 14,299
  • 26
  • 93
  • 133

1 Answers1

10

Put the complete Namespace first in a variable and then use it.

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

return new $namespace
?>

Same Topic: Can PHP namespaces contain variables?

Community
  • 1
  • 1
René Höhle
  • 26,716
  • 22
  • 73
  • 82