Examples of Namespace Use in PHP

  • 2021-12-04 18:21:40
  • OfStack

A namespace in a programming language refers to a special scope that contains identifiers under that scope and is itself an identifier. Namespaces can be mapped to the directory of the operating system. A namespace is equivalent to a directory, and the classes, functions and constants in the namespace are equivalent to files in the directory. Files in the same directory (namespace) cannot have the same name, but files with the same name can be found in different directories.

Namespaces can be used to resolve name conflicts, such as defining a class when this class has the same name as a class inside PHP or a class in a class library that include comes in. At the same time, the namespace can also improve the readability of the code. The namespace has an alias function, which can help you give an alias to a class name with a length of more than 10 characters, thus shortening the code without worrying about naming conflicts with other spaces.

In PHP, only classes, functions and constants will be affected by namespaces. After php 5.3, constants can be defined by const keywords, and before 5.3, define is used, and namespaces are only valid for const keywords.

The following php code: In the file. php file, a constant, a function, and a class are defined with namespace: (file1.php)


<?php
namespace MyProject; // Define Namespace MyProject
const A = 1;
function MyFunc(){
 return __FUNCTION__;
}
class MyClass{
 static function MyMethod(){
 return __METHOD__;
 }
}
?>

After you define the namespace, add the name of the namespace when you use it, as follows: (file2.php)


<?php
include ("file1.php");
echo MyProject\A."<br>";
echo MyProject\MyFunc()."<br>";
echo MyProject\MyClass::MyMethod();
?>

After defining the namespace, you can use different methods, variables and classes in the same file as long as it does not belong to the same namespace!

Namespaces can have multi-level schemas, as follows:

namespace MyProject\Sunname;

There can be multiple different namespaces in an php file, as follows: (file3. php)


<?php
namespace MyProject; // Define Namespace MyProject
const A = php;
function MyFunc(){
 return __FUNCTION__;
}
class MyClass{
 static function MyMethod(){
 return __METHOD__;
 }
}
// Redefine 1 Namespace 
namespace AnotherMyProject; // Define Namespace AnotherMyProject
const A = php;
function MyFunc(){
 return __FUNCTION__;
}
class MyClass{
 static function MyMethod(){
 return __METHOD__;
 }
}
?>

Not only that, you can also import the namespace with the use keyword, as shown in the following php code:


<?php
include ("file1.php");
use MyProject as ns;
echo ns\A."<br>";
echo ns\MyFunc()."<br>";
echo ns\MyClass::MyMethod();
?>

There is another thing to pay attention to, __NAMESPACE__ Constant, which is used to return the name of the current namespace, may be useful when debugging!

Summarize


Related articles: