: This article mainly introduces the example analysis of namespaceuse usage in php. if you are interested in the PHP Tutorial, refer to it. This example describes the usage of namespace use in php. We will share this with you for your reference. The details are as follows:
It seems a bit outdated now, but there are still not many people using namespace. I guess it's because I'm 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
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; // absolutely call userCenter \ login; // relatively call use userCenter \ register; // reference space use userCenter \ register as reg; // reference space and add alias
3. instance description
Login. class. php
<?phpnamespace userCenter;function check_username(){ echo "login OK
";}class login{ public function save(){ echo "login had saved
"; }}?>
Regist. class. php
<?phpnamespace userCenter\regist{ function check_username() { echo "regist OK
"; } class regist{ public function save(){ echo "regist had saved
"; } }}?>
Test. php
<? Phprequire "login. class. php "; require" regist. class. php "; use userCenter \ regist; // use to call space use userCenter \ regist as reg; // as to define the alias echo \ userCenter \ check_username (); // call $ login = new \ userCenter \ login (); echo $ login-> save (); echo regist \ check_username (); // call echo reg \ check_username (); // call the alias $ 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 hope this article will help you with PHP programming.
The above introduces the namespace use instance analysis in php, including some content, and hope to be helpful to friends who are interested in PHP tutorials.