Variable Class Names ignore “use”

我只是一个虾纸丫 提交于 2020-01-02 06:27:12

问题


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?


回答1:


You can not import with use into variable classnames. That is a limitation of PHP.

See as well the related questions:

  • Expanding PHP namespace alias to full namespace string
  • Can't get constant from dynamic class using namespaces


来源:https://stackoverflow.com/questions/13313904/variable-class-names-ignore-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!