Home >Backend Development >PHP Tutorial >Introduction to the usage of namespace in php_PHP tutorial
Speaking of this now, it feels a bit outdated, but I feel that not many people use namespaces, probably because they are not used to it.
Class organizes functions one by one, and namespace can be understood as organizing classes, functions, etc. in an orderly manner. Personally, I think the main advantages of namespace are
First, you can better manage the code
Second, with more files, you can avoid duplicate names of classes and functions
Third, code readability is enhanced
1. Define namespace
|
namespace userCenter; //php code namespace userCenterregister; //php code namespace userCenterlogin { //php code } |
Namespaces cannot be nested or declared multiple times in the same code (only the last one will be recognized). However, you can define multiple namespaced codes in the same file. It is more appropriate to define a namespace for each file (it can be the same namespace).
2. Call namespace
userCenterregister; //Absolute call
userCenterlogin; //Relative call
Use userCenterregister; //Reference space
Use userCenterregister as reg; //Reference space and add alias
3, Example
login.class.php
|
";
}
class login{
public function save(){
echo "login had saved "; } } ?> regist.class.php "; } class regist{ public function save(){ echo "regist had saved "; } } } ?> |
test.php
2 3 11 12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜>require "login.class.php";<🎜> <🎜> <🎜> <🎜>require "regist.class.php";<🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜>use userCenterregist; //使用use调用空间<🎜> <🎜> <🎜> <🎜>use userCenterregist as reg; //as定义别名<🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜>echo userCentercheck_username(); //绝对调用<🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜> <🎜>$login = new userCenterlogin();<🎜> <🎜> <🎜> <🎜>echo $login->save(); echo registcheck_username(); //相对调用 echo regcheck_username(); //别名调用 $regist = new regregist(); echo $regist->save(); |