Now say this, feeling a bit outdated, but the feeling with namespace people still not much, estimated or because not accustomed to it.
class to organize a function, namespace can be understood as a class,function, such as orderly organization. Personally feel that the main advantages of namespace are
First, you can better manage your code
Second, a lot of documents, you can avoid the duplicate name of Class,function
Third, code readability has been enhanced
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 Usercenterregister; Php code namespace Usercenterlogin {//php code} |
namespaces cannot be nested or declared multiple times at the same code (only the last time it will be recognized). However, you can define multiple namespaces in the same file, and it is more appropriate for each file to define a namespace (which 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 aliases
3, example 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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60-61 |
<?php namespace Usercenter; function Check_username () {echo "Login ok<br>"; Class login{Public Function Save () {echo "Login had saved<br>"; }?> regist.class.php <?php namespace Usercenterregist {function check_username () {echo reg ist ok<br> "; Class regist{Public Function Save () {echo "regist had saved<br>"; }}}?> |
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 |
<?php require "login.class.php"; Require "regist.class.php"; Use usercenterregist; Use invoke space using Usercenterregist as REG; As definition alias Echo usercentercheck_username (); Absolute call $login = new Usercenterlogin (); echo $login->save (); Echo Registcheck_username (); Relative invocation of Echo regcheck_username (); Alias Call $regist = new Regregist (); echo $regist->save (); |
Using use, which is better than absolute invocation, is like adding a prefix to class,function, so it looks clearer.