Namespace usage in php. The usage of namespace in php is a bit outdated, but there are still not many people using namespace. it is estimated that I am not used to it. Class introduces the usage of namespace in one php namespace
Now, I feel a little out of date, but I still feel that there are not many people using namespace. it is probably because I am not used to it.
Class organizes functions one by one. namespace can be understood as an orderly organization of classes and functions. I personally think the main advantages of namespace are:
First, better code management
Second, if there are more files, the duplicate names of the class and function can be avoided.
Third, enhanced code readability
1. define namespace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Namespace userCenter; // Php code Namespace userCenter \ register; // Php code Namespace userCenter \ login { // Php code } |
The namespace cannot be nested or declared multiple times in the same code (only the last one will be recognized ). However, you can define multiple namespace-based codes in the same file. a proper practice is to define a namespace (or the same namespace) for each file ).
2. call namespace
\ UserCenter \ register; // An absolute call
UserCenter \ login; // relative call
Use userCenter \ register; // reference space
Use userCenter \ register as reg; // reference the space and add an alias
3. instance description
Login. class. php
1 2 3 4 5 6 7 8 9 10 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
Namespace userCenter; Function check_username (){ Echo "login OK "; } Class login { Public function save (){ Echo "login had saved "; } } ?> Regist. class. php Namespace userCenter \ regist { Function check_username (){ Echo "regist OK "; } Class regist { Public function save (){ Echo "regist had saved "; } } } ?> |
Test. php
1 2 3 4 5 6 7 8 9 10 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 userCenter \ regist; // use to call a space Use userCenter \ regist as reg; // as defines the alias Echo \ userCenter \ check_username (); // call absolutely $ Login = new \ userCenter \ login (); Echo $ login-> save (); Echo regist \ check_username (); // relative call Echo reg \ check_username (); // alias call $ Regist = new reg \ regist (); Echo $ regist-> save (); |
It is better to use it than to call it. it is like adding a prefix to class and function. This makes it clearer.
I think this is a bit outdated, but I still feel that there are not many people using namespace. it is probably because I am not used to it. Class One by one...