尝试加载课程" Class"来自全局命名空间。错误Symfony2

时间:2016-10-03 10:13:18

标签: symfony

嗨,我有一个班级名称"客户"在一个变量中:

Ubuntu-Env

现在,我已在运行时在服务文件中为此类创建了对象:

git rebase

现在我收到以下错误:

$myclass = "Customer";

甚至namespace MyBundle\Service; use Doctrine\ORM\EntityManager; use Doctrine\ORM\QueryBuilder; use MyBundle\Component\Data\handle\Customer; use Symfony\Component\HttpFoundation\Request; class MyServices { private $em; public function __construct(EntityManager $entityManager) { $this->em = $entityManager; } public function getClassCustomer($className) { $object = new $className(); } } 类已经定义并包含在同一个文件中:

请提出可能存在的问题。 提前谢谢

1 个答案:

答案 0 :(得分:1)

问题在于,当您将变量用作类名时,use语句不适用。

当你这样做时

use MyBundle\Component\Data\handle\Customer;
new Customer();

已解决为

new MyBundle\Component\Data\handle\Customer();

但是有了这个:

use MyBundle\Component\Data\handle\Customer;
$className = "Customer";        
$object = new $className();

它仍然只是:

$object = new \Customer();

看一下Example #3 on this page类似的情况:

use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a;      // instantiates object of class Another