Home > Article > Backend Development > Introduction to php namespaces
Why use namespaces? As the number of files in the project increases, it is inevitable that class names, function names, and constant names will be repeated. This article mainly shares with you an introduction to PHP namespaces, hoping to help everyone.
未定义命名空间的如下图
Fatal error: Cannot redeclare class test in E:\PHP\PHPTutorial\WWW\demo\namespace\b.php on line 2
Define three files
a.php
namespace a\b;
class test{ public function show(){ echo 'this is a'; }}
b.php
<?phpnamespace c\d;class test{ public function show(){ echo 'this is b'; }}
index.php require './a.php'; require './b.php';
$a = new a\b\test ();When instantiating a class, remember to add the namespace
Since it is more cumbersome every time to instantiate the class, you can use the second way of writing
ba0bf9f6a66d5f65ad2b51a4d38cbdb0show();
1. The overall import of the space requires an alias. If there is no alias, the character after the last \ is used as the space name by default
The code behind namespace All belong to the current space, and the code outside the namespace belongs to the global space.
How to use the global space in the current space, just add \ backslash after the required members to indicate the global space.
Related recommendations:
Detailed explanation of PHP namespace and automatic loading examples
Completely master the PHP namespace
Detailed usage of PHP namespace
The above is the detailed content of Introduction to php namespaces. For more information, please follow other related articles on the PHP Chinese website!