问题描述
从其他帖子中看来,如果您定义了名称空间,并且想要在另一个名称空间中动态创建对象,则必须构造一个字符串并在新调用中使用它.但是,我的行为很奇怪.似乎该方法无法跨命名空间使用.
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:
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();
有人知道为什么在使用变量作为类名时,需要在变量中使用完全限定的名称空间,但是经过硬编码后,我才能利用"use"命令吗?
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?
推荐答案
You can not import with use
into variable classnames. That is a limitation of PHP.
也请参阅相关问题:
- Expanding PHP namespace alias to full namespace string
- Can't get constant from dynamic class using namespaces
这篇关于变量类名忽略"use".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!