This article introduces the content of the PHP namespace (namespace), has a certain reference value, now share to everyone, the need for friends can refer to
Namespaces Overview
What is a namespace? In a broad sense, namespaces are a way of encapsulating things. This abstract concept can be seen in many places. For example, in an operating system, a directory is used to group related files, and for files in a directory, it plays the role of a namespace. For example, file Foo.txt can exist in both directory/home/greg and/home/other, but there cannot be two foo.txt files in the same directory. In addition, when accessing the Foo.txt file outside of directory/home/greg, we must place the directory name and directory delimiter before the file name to get/home/greg/foo.txt. The application of this principle to the field of programming is the concept of namespaces.
In PHP, namespaces are used to solve two types of problems encountered when writing a class library or application to create reusable code such as classes or functions:
User-written code conflicts with the name of a class/function/constant or third-party class/function/constant inside PHP. Creates an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem), improving the readability of the source code.
namespaces provide a way to group related classes, functions, and constants together. The following is an example of a PHP namespace syntax:
My project directory structure is as follows:
index.php
If you need to use both test1\Test.php
and test2\Test.php
, if you do not have a namespace, because two classes have the same name, you will get an error.
vendor\test1\test.php
<?phpnamespace vendor\test1;class test{Public function path () { echo __dir__. <br> "; }}
vendor\test2\test.php
<?phpnamespace vendor\test2;class test{Public function path () { echo __dir__. <br> "; }}
index.php
<?php spl_autoload_register (function ($class) { if ($class) { $file = str_replace (' \ \ ', '/', $class); $file. = '. php '; if (file_exists ($file)) { include ($file);}} ); $test = new \vendor\test1\test (); $test->path (); $test 2 = new \vendor\test2\test (); $test 2->path ();
The output is as follows:
D:\www\learning\vendor\test1d:\www\learning\vendor\test2
Global namespaces
If no namespace is defined, all classes and functions are defined in the global space, as before the introduction of the namespace concept in PHP. Precede the name with a prefix \ means that the name is the name in the global space, even if the name is in a different namespace.