使用字符串创建PHP类实例到Symfony2

时间:2015-04-07 18:20:44

标签: php symfony inheritance

我需要将不同的对象实例化为同一个方法。 我在这里找到了解决方案:

Creating PHP class instance with a string

但是当我在Controller of Symfony2上使用它时,我有这个错误:

尝试加载类" PhotoType"来自全局命名空间。 你忘记了"使用"声明?

我不明白,因为我添加了所有"使用"

namespace DIVE\FileUploaderBundle\Controller;

use DIVE\FileUploaderBundle\Entity\Photo;
use DIVE\FileUploaderBundle\Form\PhotoType;
...

class DefaultController extends Controller {

    public function listFileAction($fileType) {
        $em = $this->getDoctrine()->getManager();
        $repository = $em->getRepository("FDMFileUploaderBundle:".$fileType);
        $files = $repository->findAll();

        $forms = array();
        foreach ($files as $file) {
            $class = $fileType."Type";
            array_push($forms, $this->get('form.factory')->create(new $class(), $file));
        }

        $formViews = array();
        foreach ($forms as $form) {
            array_push($formViews, $form->createView());
        }

        return $this->render("FDMFileUploaderBundle:Default:list".$fileType.".html.twig", array(
            "forms" => $formViews
            )
        );
    }
}

对不起我的英语,我正在学习它。

2 个答案:

答案 0 :(得分:5)

试试这个:

foreach ($files as $file) {
    $class = 'DIVE\FileUploaderBundle\Form\' . $fileType . 'Type';
    // ...
}

实际上,您可以在 last comment 中找到与您所关联的问题的接受答案中的答案:

  

请注意,在使用命名空间时,您必须提供完整路径:$className = '\Foo\Bar\MyClass'; $instance = new $className(); - Giel Berkers 2014年12月16日8:23

基本上,为了从字符串中实例化一个类,必须使用类的完全限定名称 - 包括命名空间。查看PHP手册中的 Namespaces and dynamic language features 页面,以获得快速解释和示例。

答案 1 :(得分:1)

根据http://php.net/manual/en/language.namespaces.dynamic.php

  

必须使用完全限定名称(带名称空间前缀的类名)。请注意,因为动态类名,函数名或常量名中的限定名和完全限定名之间没有区别,所以不需要前导反斜杠。