猿问

在编程的时候遇到这样一个关于命名空间的问题,先上代码:

namespace Test {    class Test {}
}namespace Chou {    use Test\Test;    class Mee {        public $class = 'Test';        public function getClass()
        {            return new $this->class();
        }
    }

    $tmp = new Mee();
    $tmp->getClass();
}

我试图在getClass方法中通过变量动态实例化另一个命名空间的类,但是触发了“Class not found”错误。我觉得时$class变量的问题,所以又把测试代码简化了一下:

namespace Chou {    use Test\Test;    $test = 'Test';    $tmp = new $test();
}

果然出现了和预期一样的错误。我知道可以通过完全限定的方式来解决,但是我仍然想明白这是什么原理,还望高手解惑。


Smart猫小萌
浏览 93回答 1
1回答

波斯汪

PHP手册里有写,在变量中使用命名空间必须使用完全限定名称,规定如此。
随时随地看视频慕课网APP
我要回答