This article mainly introduces how to define the namespace of the PHP namespace, and analyzes in detail the definition methods and precautions of the namespace and sub-namespace of the php namespace in combination with the instance form, for more information about how to define the namespace of a PHP namespace, the definitions and precautions of php namespaces and sub-namespaces are analyzed in detail based on the instance form. For more information, see
This document describes how to define the namespace of a PHP namespace. We will share this with you for your reference. The details are as follows:
Define a namespace
I don't want to explain the name of a space here. a better explanation is to prove it using an example:
For example:
The following code is a file in "test. php:
Namespace Test; class Test {public function Ttest () {echo "this is the Test method in Test "."
";}}
Next, I will use three different access methods. I will write these three access programs in a file named "index. php:
Method 1:
namespace Index;require 'test.php';$T=new \Test\Test();$T->Ttest();
The result is:
This is the Test method in Test.
Method 2:
namespace Index;namespace Test;require 'test.php';$T=new Test();$T->Ttest();
The result is:
This is the Test method in Test.
Method 3:
namespace Index;require 'test.php';use Test\Test;$T=new Test();$T->Ttest();
The result is:
This is the Test method in Test.
Note: namespace Index can be written or not written. this is only the name of the index. php file space. The results of these three methods are the same.
Define a sub-namespace
Definition:
It has a similar relationship with directories and files. The PHP namespace also allows you to specify a hierarchical namespace name. Therefore, namespace names can be defined in different layers.
For example, this is my custom project directory:
One. php
namespace projectOne\one;class Test{ public function test(){ return "this is a test program"; }}
To access the Test () method under the test class in one. php, the code in Two is as follows:
Two. php
namespace projectOne\one;require '../projectOne/One.php';$O=new Test();echo $O->test();
Output: this is a test program
Define multiple namespaces in the same file and access each other
Test. php
namespace projectOne\one{ class test{ public function hello(){ return "helloworld"; } }}namespace projectOne\Two{ class project{ public function world2(){ return "welcome to china"; } } class project2 extends \projectOne\one\test{ public function wo(){ return "this is my test function ,it is name wo"; } }}namespace projectOne\Two{ $p=new project2(); echo $p->wo()."
"; echo $p->hello();}
Output: this is my test function, it is name wo
Helloworld
The above is a detailed description of the namespace definition method of the PHP namespace. For more information, see other related articles in the first PHP community!