PHP supports two abstract methods of accessing the inner elements of the current namespace, __namespace__ Magic constants and NAMESPACE keywords.
The value of the constant __namespace__ is a string containing the name of the current namespace. In the global, not included in any namespace code, it contains an empty string.
Example #1 __namespace__ example, the code in the namespace
<?php namespace MyProject; Echo ' "', __namespace__, '"; Output "MyProject"?>
Example #2 __namespace__ example, Global code
<?php Echo ' "', __namespace__, '"; Output ""?>
Constant __namespace__ is useful when creating names dynamically, for example:
Example #3 Create names dynamically using __namespace__
<?php namespace MyProject; function Get ($classname) { $a = __namespace__. '\\' . $classname; return new $a; }? >
The keyword namespace can be used to explicitly access elements in the current namespace or in a sub-namespace. It is equivalent to the self operator in the class.
Example #4 namespace operator, code in the namespace
<?php namespace MyProject; Use Blah\blah as mine; Namespace aliases (refer to: Using namespace aliases and imports) blah\mine ();//Call Function Blah\blah\mine () namespace\blah\mine ();//Call Function Myproject\blah \mine () namespace\func ();//Call Function Myproject\func () namespace\sub\func ();//Call Function Myproject\sub\func () Namespace\cname::method (); Call the static method of the class Myproject\cname "method" $a = new Namespace\sub\cname ();//Instantiate the Class Myproject\sub\cname object $b = Namespace\constant; Assigns the value of the constant myproject\constant to the $b?>
Example #5 namespace operator, global code
<?php Namespace\func (); Call function func () namespace\sub\func ();//Call Function Sub\func () namespace\cname::method ();//Call the static method of the class CNAME c11/> $a = new Namespace\sub\cname (); Instantiate the Sub\cname class object $b = namespace\constant;//assigns the value of the constant CONSTANT to the $b?>