1

Why do I receive an error without using a fully qualified name for Bar?

Foo.php

<?php
namespace Bla\Bla;
require '../../vendor/autoload.php';

class Foo
{
    public function getBar()
    {
        $className="Bar";
        $fullClassName='\Bla\Bla\\'.$className;

        $obj1=new Bar();            //Works

        $obj2=new $fullClassName(); //Works

        $obj3=new $className();     //ERROR.  Class Bar not found
    }   
}

$foo=new Foo();
$foo->getBar();

Bar.php

<?php
namespace Bla\Bla;
class Bar {}

2 Answers 2

1
$obj1=new Bar();

The statement will work because Bar is defined in namespace Bla\Bla that you are already in.


$obj2=new $fullClassName();

This will work because you are referring to the class from the global namespace.


$obj3=new $className();

This will not work because you try to initiate class Bar from a string, in which the current namespace Bla\Bla is not prepended to the class name.

It would work if you define a class Bar inside the global namespace.

#Bar.php
<?php
  namespace Bla\Bla{
    class Bar {}
  }
  namespace {
    class Bar {
      public function __construct(){ echo 'Hi from global ns!';}
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You have to use the full namespace of the class. Try this: (not tested)

$className="Bla\\Bla\\Bar";

In case the namespace is Bla\Bla.

4 Comments

I was able to get it to work as shown in the original post (see my $obj1 and $obj2 examples), but I am asking "why".
I guess it is because the interpreter has to parse the text value without any context. It cannot know which "Bar" you are refereeing to without having the full namespace. What if you had two different "Bar" classes, each in its own namespace?
But $obj1=new Bar(); works. Isn't this the same thing?
I think it depends how the PHP interpreter is implemented. When the interpreter process the "Bar" token, it already has a semantic property which relates it to a specific class object (which was produced during the semantic analysis of the code, and not in runtime). However, when the interpreter process a string variable at runtime, it cannot relate the string content to any class without you telling it exactly which class. These are my two cents..

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.