This paper mainly introduces the use usage of namespace namespace in PHP, and analyzes the definition and usage of namespace in PHP in the form of instance, and needs friends to refer to it. We hope to help you.
Specific as follows:
Now say this feeling a bit out of date, but feel with namespace of people still not much, estimate or because not accustomed to it.
Class organizes a function together, namespace can be understood to organize a class,function and so on in an orderly manner. Personally feel that namespace's main advantage is
First, you can better manage your code
Second, more than one file, you can avoid the duplicate name of Class,function
Third, the readability of the code is enhanced
1. Define Namespace
Namespace usercenter;//php code namespace usercenter\register;//php code namespace Usercenter\login {//php code}
namespaces cannot be nested or declared multiple times at the same code (only the last time they are recognized). However, you can define multiple namespaces in the same file, and it's a good idea to define a namespace (which can be the same namespace) for each file.
2. Call namespace
\usercenter\register; Absolutely call Usercenter\login; Relative invocation of Use usercenter\register; Reference space use Usercenter\register as Reg; referencing space and adding aliases
3. Example Description
login.class.php
<?phpnamespace usercenter;function Check_username () {echo "Login ok<br>";} Class login{Public Function Save () {echo "Login had saved<br>";}}? >
regist.class.php
<?phpnamespace usercenter\regist{function Check_username () {echo "Regist ok<br>";} class regist{Public functi On save () {echo "regist had saved<br>";}}? >
test.php
<?phprequire "login.class.php"; require "regist.class.php"; use usercenter\regist; Using the use call space uses Usercenter\regist as REG; As definition alias Echo \usercenter\check_username (); Absolute call $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 ();
Using use is a bit better than an absolute call, like adding a prefix to class,function and so on, which looks more clear.
Related recommendations:
A brief analysis of namespace-related concepts in PHP
PHP Namespaces and auto-load classes
Basics of using PHP namespaces