The previous article introduced some terms of the PHP namespace and Its parsing rules. In this article, we will continue to describe the PHP namespace dynamic access and usage skills, hoping to help
The previous article introduced some terms of the PHP namespace and Its parsing rules. In this article, we will continue to describe the PHP namespace dynamic access and usage skills, hoping to help
The namespace of PHP is one of the most important new features added to PHP 5.3. This concept has been available in C # for a long time, the namespace in php is actually the same as that in c.
1. Dynamically Access namespace Elements
Namespace me \ poet; function test () {echo '000000';} $ fun = 'test'; // It cannot be used. Last $ fun () cannot dynamically Call test (): Fatal error: Call to undefined function test () $ fun = '\ me \ poet \ test '; // correct // $ fun = 'me \ poet \ test'; // correct $ fun ();
That is to say, dynamic calling must be a limited name or a fully qualified name (concept reference: Use of PHP namespaces)
2. Magic constants and operators
Namespace me \ poet; function test () {echo '1';} echo _ NAMESPACE __; // magic constant: namespace name (output me \ poet) // namespace OPERATOR: explicitly accesses the elements in the current namespace or sub-namespace. It is equivalent to the self operator \ me \ poet \ test (); namespace \ test () in the class (); // The above two lines of code are equivalent.
Iii. Alias, import, and global space (including multiple examples)
Namespace ws \ weichen \ www; use ws \ weichen \ www as poet; // define the alias poet // use ws \ weichen \ www; // do not add, then take the last alias (www) function demo () {echo '1';} \ ws \ weichen \ www \ demo (); poet \ demo (); // www \ demo (); // This is called if no as is added
The above three lines of code have the same effect.
Benefits of naming by rules (ws \ weichen \ www): If you change the domain name, you only need to change the prefix name without affecting the use of the alias www in the code below.
/* Import */include 'Hello. class. php '; use \ ws \ weichen \ www; use \ Hello;/* -------------------------------------------------------- * // * supports multiple use statements */use \ nihao \ shijie as hello, \ ws \ weichen \ www;/* ------------------------------------------------------ * // * Global Space: backslash call */namespace A \ B \ C; // This function is A \ B \ C \ fopen (); function fopen () {$ f = \ fopen('demo.txt '); // call the global fopen function return $ f ;}