在 Symfony2 中创建带有字符串的 PHP class 实例

Creating PHP class instance with a string into Symfony2

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

Creating PHP class instance with a string

但是当我在 Symfony2 的控制器上使用它时,出现了这个错误:

试图从全局命名空间加载 class "PhotoType"。 您是否忘记了 "use" 语句?

我不明白,因为我已经添加了我所有的 "use"

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
            )
        );
    }
}

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

试试这个:

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

实际上,您可以在您链接到的问题的已接受答案的 last comment 中找到答案:

Please note the when using namespaces, you must supply the full path: $className = '\Foo\Bar\MyClass'; $instance = new $className();Giel Berkers Dec 16 '14 at 8:23

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

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

One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.