"using namespaces with classes created from a variable" Code Answer

4

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 foobaz

therefore, all "string class names" are always absolute and need to be written as fqn:

$class = 'foobaz';

(note: no leading .)

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

$class = __namespace__ . 'baz';
By iMoeNya on March 19 2022

Answers related to “using namespaces with classes created from a variable”

Only authorized users can answer the Search term. Please sign in first, or register a free account.