olive007
olive007

Reputation: 850

Creating PHP class instance with a string into Symfony2

I need to instance different object into a same method. I have found soluce here:

Creating PHP class instance with a string

But when I use that on Controller of Symfony2 I have this error :

Attempted to load class "PhotoType" from the global namespace. Did you forget a "use" statement?

I didn't understand because I have add all of my "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
            )
        );
    }
}

Sorry for my English, I am learning it.

Upvotes: 1

Views: 4928

Answers (2)

MikO
MikO

Reputation: 18741

Try this:

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

Actually you could find the answer in the last comment of the accepted answer to the very question you linked to:

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

Basically, in order to instantiate a class from a string, you must use the fully qualified name of the class - including the namespace. Check the page Namespaces and dynamic language features from PHP Manual for a quick explanation and examples.

Upvotes: 5

Greg
Greg

Reputation: 803

According to 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.

Upvotes: 1

Related Questions