1

Hi I have a class name "Customer" in a variable like:

$myclass = "Customer";

Now I have created object for this class at run time inside a service file:

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

Now I am getting following error:

Attempted to load class "Customer" from the global namespace

Even Customer class is already defined and included in the same file:

Please suggest what could be the Issue. thanks in advance

2
  • Youre explanation is a bit chaotic. Please post minimal but full code snippet that will let us reproduce the issue. use/BundleName/ClassFolder: is not including anything. Commented Oct 3, 2016 at 10:19
  • Hi dragoste: actualy namespace Mybundle\Service; use Mybundle\Component\DataFolder\Classess\Customer; I am using on the top of file: Commented Oct 3, 2016 at 10:23

1 Answer 1

1

The issue is that when you're using variable as class name, then use statement doesn't apply.

When you do

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

It's resolved as

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

But with this:

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

It's still just:

$object = new \Customer();

Take a look Example #3 on this page as it's similar case:

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
Sign up to request clarification or add additional context in comments.

2 Comments

My class name is dynamic: it will be any class like customer and some time user etc.. then in this case?
You need full qualified class name in your variable (with full namespace).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.