This article mainly introduced the Php namespace namespace definition method, combined with the instance form detailed analysis Php namespace namespace and the sub-namespace definition method and the related attention matters, the need friend can refer to the next
This article describes the method of defining PHP namespace namespace. Share to everyone for your reference, as follows:
Define namespaces
For the name of the space, I would like to use no text to explain, a better explanation is to prove with an example:
For example:
The following code is the file in "test.php":
namespace Test;class test{public function Ttest () { echo "This is test method in test". <br> "; }}
Next I will visit in three different ways, I write these three access programs in a file called "index.php":
Method One:
namespace Index;require ' test.php '; $T =new \test\test (); $T->ttest ();
The resulting result is:
This is the test method in test.
Method Two:
namespace Index;namespace test;require ' test.php '; $T =new Test (); $T->ttest ();
The resulting result is:
This is the test method in test.
Method Three:
namespace Index;require ' test.php '; use test\test; $T =new test (); $T->ttest ();
The resulting result is:
This is the test method in test.
Note: namespace index can be written without writing, this is just the space name of the index.php file. The results of these three methods are the same.
Defining child namespaces
Defined:
As with directories and files, the PHP namespace allows you to specify the name of a hierarchical namespace. Therefore, the name of the namespace can be defined in a hierarchical manner.
For example, this is my custom project directory:
one.php
namespace Projectone\one;class test{public function Test () { return ' this was a Test program '; }}
In order to access the test () method under the test class in one.php, my code in both is as follows:
two.php
Namespace Projectone\one;require '. /projectone/one.php '; $O =new Test (); Echo $O->test ();
Output:this is a test program
Multiple namespaces are defined in the same file, and they are accessed from 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 was my test function, it is Name Wo ";}} } namespace projectone\two{ $p =new project2 (); echo $p->wo (). " <br> "; echo $p->hello ();}
Output:this is my test function, it is name wo
HelloWorld