In PHP, a function with the same name or a class with the same name is not allowed. For prevents programmers from repeating conflicting class names or function names defined in the project, the concept of namespaces was introduced in PHP5.3.
1. Namespaces, the code is divided into different space, the class names of different spaces are independent of each other, non-conflicting. There can be more than one namespace in a php file and no code in front of the first namespace. The code after the content space declaration belongs to this namespace , for example:
<?phpecho 111; Due to namespace before the code and error namespace Teacher;class person{ function __construct () { echo ' please study! '; }
2. Calling a class or method in a different space requires specifying a namespace. For example:
<?phpnamespace teacher;class person{ function __construct () { echo ' please study!<br/> '; }} function person () { return ' You must stay here! ';}; namespace Student;class person{ function __construct () { echo ' I want to play!<br/> '; }} New person (); This space (student space) new \teacher\person (); Teacher Space New \student\person (); Student Space Echo \teacher\person (); person function under teacher space
Output:
I want to play! Please study! I want to play! You must stay here!
3. The introduction of other files within a namespace does not belong to this namespace, but to public spaces or namespaces defined in the file itself. Example:
First define a 1.php and 2.php file:
<?php //1.phpclass person{function __construct () { echo ' I am one!<br/> '; }}
<?phpnamespace newer;require_once './1.php '; new person (); Error, can not find person;new \person (); Output I am tow!;
<?php //2.phpnamespace twoclass person{function __construct () { echo ' I am tow!<br/> '; }}
<?phpnamespace new;require_once './2.php '; New person (); Error, (current space) can not find person;new \person (); Error, (public space) can not find person;new \two\person (); Output I am tow!;
4. Let's take a look at how use is used: (using alater reference can be abbreviated)
namespace School\parents;class man{ function __construct () { echo ' Listen to teachers!<br/> '; }} namespace School\teacher;class person{ function __construct () { echo ' please study!<br/> '; }} namespace School\student;class person{ function __construct () { echo ' I want to play!<br/> '; }} New person (); Output I want to play!new \school\teacher\person (); Output study!new Teacher\person (); Error----------use School\teacher;new Teacher\person (); Output study!----------use School\teacher as Tc;new Tc\person (); Output study!----------use \school\teacher\person;new person (); Error----------use \school\parent\man;new man (); Error