Using namespaces with classes created from a variable

Because strings can be passed around from one namespace to another. That makes name resolution ambiguous at best and easily introduces weird problems.

namespace Foo;

$class="Baz";

namespace Bar;

new $class;  // what class will be instantiated?

A literal in a certain namespace does not have this problem:

namespace Foo;

new Baz;     // can't be moved, it's unequivocally \Foo\Baz

Therefore, all “string class names” are always absolute and need to be written as FQN:

$class="Foo\Baz";

(Note: no leading \.)

You can use this as shorthand, sort of equivalent to a self-referential self in classes:

$class = __NAMESPACE__ . '\Baz';

Leave a Comment