Namespaces Flashcards
What two problems are namespaces designed to solve?
- 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.
PHP namespaces provide a way in which to group related…
…classes (including abstracts and traits), interfaces, functions, and constants.
What can’t you use as a namespace name?
PHP, php, and compound names starting with these words.
Where is a namespace declared?
At the top of the file, before any code, with one exception: the declare keyword. No non-php code can precede a namespace declaration, not even whitespace.
Can multiple namespaces be declared in the same file?
Yes. There are two allowed syntaxes, but bracketing the namespaces is the better syntax. However, using multiple namespaces in one file is strongly discouraged.
How do you combine global non-namespaced code with namespaced code, in the same file?
To do so, only bracketed namespace syntax is supported. Global code should be encased in a namespace statement with no namespace name:
namespace { //global code
$a = 1;
}
No PHP code may exist outside of the namespace brackets, except for an opening declare statement.
What are the three ways to which a class can be referred?
- Unqualified name: $a = new foo();
- Qualified name: $a = new subspacename\foo();
- Fully qualified name: $a = new \currentnamespace\foo();
How can you access any global class, function, or constant, within a namespace?
A fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.
What are the two ways that PHP supports for abstractly accessing elements within the current namespace?
The __NAMESPACE__ magic constant, and the namespace keyword.
What is the value of __NAMESPACE__?
A string that contains the current namespace name.
In global, un-namespaced code, what does __NAMESPACE__ contain?
An empty string.
The namespace keyword is the namespace equivalent of the ____ operator for classes.
The namespace keyword is the namespace equivalent of the self operator for classes.
What does this code do?
namespace MyProject
namespace\cname::method();
It calls the static method “method” of class MyProject\cname.
What is namespace aliasing/importing?
The ability to refer to an external fully qualified name with an alias. It’s like a symlink.
What are the three kinds of namespace aliasing or importing?
Aliasing a class name, aliasing an interface name, and aliasing a namespace name.