Namespaces Flashcards
What two problems are namespaces designed to solve in PHP?
- Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
- Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
What are namespaces in PHP?
A way to group related classes, interfaces, functions and constants.
What namespace names are reserved for internal language?
Namespace names PHP and php, and compound names starting with these names (like PHP\Classes).
Which types of code are affected by namespaces?
Classes (including abstracts and traits), interfaces, functions and constants.
How are namespaces declared?
With the “namespace” keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the “declare” keyword, for defining encoding of a source file.
Can non-php code precede a namespace declaration?
No. Not even extra whitespace.
Can the same namespace be defined in multiple files?
Yes.
Can namespaces be defined with sublevels, to specify a hierarchy of namespace names?
Yes, like this:
namespace MyProject\Sub\Level;
Can multiple namespaces be declared in the same file?
Yes. There are two allowed syntaxes. With one you just declare multiple namespaces in a file. With the other, recommended method, you declare it like a function, with the namespace name followed by a braced section of code.
How can global non-namespaced code be combined with namespaced code in a single file?
By using bracketed syntax. Global code should be enclosed in a namespace statement with no namespace name, just the “namespace” keyword.
Regarding namespaces, what are the three ways that a class can be referred to in PHP?
- Unqualified name: $a = new foo() or foo::staticmethod(). If the current namespace is currentnamespace, this resolves to currentnamespace\foo.
- Qualified name: $a = new subnamespace\foo() or subnamespace\foo::staticmethod(). If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo.
- Fully qualified name: $a = new \currentnamespace\foo() or \currentnamespace\foo::staticmethod(). This always resolves to the literal name specified in the code.
How can you access global classes, functions, or constants from within a namespace?
Use a fully qualified name, like \strlen() or \INI_ALL.
What is the value of __NAMESPACE__?
A string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.
What are the three kinds of aliasing or importing that PHP supports with namespaces?
Aliasing a class name, aliasing an interface name, and aliasing a namespace name.
How is aliasing accomplished?
With the “use” operator.