PHP namespaces (namespaces) were added in PHP 5.3, if you have learned C# and Java, namespaces are nothing new. However, it still has a very important meaning in PHP.
PHP namespaces can solve two types of problems:
name conflicts between user-written code and classes/functions/constants inside PHP or third-party classes/functions/constants.
Create an alias (or short) name for very long identifier names (usually defined to alleviate the first type of problems), improving the readability of the source code.
Reference source: http://www.w3cschool.cn/php/b298tfl0.html
PHP 7 can import classes, functions and constants from the same namespace with a use:
Reference source: http://www.w3cschool.cn/php/php-use-statement.html
<?php //inc.php documentation for testing namespace Aaa\Bbb; class MyClass{ public $val = 'Who reads and asks you to recite,'; static $val2 = 'The water falls and the fragrance floats. '; function myFun(){ return 'onestopweb.iteye.com'; } }
<?php header('Content-Type:text/html;charset=utf-8'); //The first, use the full name to access require 'inc.php'; $myClass = new \Aaa\Bbb\MyClass(); echo $myClass->val; echo $myClass::$val2; echo $myClass->myFun();
<?php //Second, use namespace to access namespace Aaa\Bbb; //Adjust the current script to the ns domain of Aaa\Bbb, and the namespace declaration must be in the first sentence header('Content-Type:text/html;charset=utf-8'); require 'inc.php'; $myClass = new MyClass(); echo $myClass->val; echo $myClass::$val2; echo $myClass->myFun();
<?php header('Content-Type:text/html;charset=utf-8'); //The third use use to access require 'inc.php'; use Aaa\Bbb\MyClass; //This way MyClass is equal to Aaa\Bbb\MyClass $myClass = new MyClass(); echo $myClass->val; echo $myClass::$val2; echo $myClass->myFun();
<?php header('Content-Type:text/html;charset=utf-8'); //Fourth use use as to access require 'inc.php'; use Aaa\Bbb as AB; //AB = Aaa\Bbb $myClass = new AB\MyClass(); echo $myClass->val; echo $myClass::$val2; echo $myClass->myFun();
Effect picture: