<?php namespace A; Use BC; C::bar();
This will throw this error: Class ‘BC’ not found
(use working)
<?php Use BC; namespace A; C::bar();
This will throw this error: Class ‘AC’ not found
(use not working)
The manpage says:
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations.
If the use keyword has to come before the namespace, shouldn’t it throw a compile error or a warning otherwise? Or what exactly happens if the use keyword is used before the namespace keyword? Does namepsace keyword reset the imports done with the use keyword?
Advertisement
Answer
use
applies to the namespace it was declared in. Thus, your first example means, “For code in the A
namespace, C
means BC
,” and your code is in the A
namespace, so the alias triggers. Your second example means, “For code in no namespace, C
means BC
,” but your code is in the the A
namespace, so the alias does not trigger. It might help to think of your examples like this:
namespace A { use BC; C::bar(); }
And:
use BC; namespace A { C::bar(); }