Reputation: 420
From other posts, it appears that if you have namespaces defined and want to dynamically create an object in another namespace, you have to construct a string and use that in the new call. However, I'm getting a weird behavior. It appears that this method does not work going across namespaces.
User.php:
namespace application\models;
class User {
public function hello() {
echo "Hello from User!";
}
}
Controller.php:
namespace application\controllers;
use application\models;
require('User.php');
$userStr = 'models\\User';
//$userOne = new $userStr(); //Doesn't work. Gets a "Class 'models\User' not found" error
$userOne = new models\User(); //Works fine
$userStr = '\\application\\models\\User';
$userTwo = new $userStr(); //Works fine
$userOne->hello();
$userTwo->hello();
Any idea why when using a variable for the class name, I need to use the fully qualified namespace when it's in a variable, but hard coded, I can leverage the "use" command?
Upvotes: 4
Views: 823
Reputation: 197757
You can not import with use
into variable classnames. That is a limitation of PHP.
See as well the related questions:
Upvotes: 3