Easy Tutorial
❮ Android Tutorial Touchlistener Ontouchevent Redis Intro Data Structure ❯

PHP Namespace Usage Guide

Category Programming Techniques

The primary purpose of a namespace is to resolve naming conflicts. PHP does not allow two functions or classes to have the same name, which would result in a fatal error. In such cases, avoiding naming repetition can solve the problem, and the most common approach is to agree on a prefix.

For example: In a project, there are two modules: article and message board, each with a class called Comment for handling user comments. Later, I might want to add some statistical functions for all user comments, such as getting the total number of comments. At this time, it would be a good practice to call the methods provided by their respective Comment classes. However, it is obviously not feasible to import both Comment classes at the same time, as the code would fail, and rewriting any Comment in another place would reduce maintainability. Then, the only option is to refactor the class names. I have agreed on a naming rule, adding the module name in front of the class name, like this: Article_Comment, MessageBoard_Comment.

It can be seen that the names have become very long, which means that more code will be written when using Comment in the future (at least more characters). Moreover, if more integrated functions are added to each module in the future, or if there is cross-calling, and a naming conflict occurs, it will be necessary to refactor the names. Of course, if this issue is noticed at the beginning of the project and a naming rule is stipulated, it can be well avoided. Another solution to consider is to use namespaces.

Note: The constants mentioned in this article: The const keyword can be used outside of classes in PHP5.3. Both const and define are used to declare constants (their differences are not detailed here), but in a namespace, define has a global effect, while const is effective in the current space. The constants I mentioned in the article refer to constants declared using const.

Basics

A namespace divides the code into different spaces (areas), and the names of constants, functions, and classes (for the sake of simplicity, I will refer to them as elements below) in each space do not affect each other, which is somewhat similar to the concept of 'encapsulation' we often mention.

To create a namespace, the namespace keyword is required, like this:

<?php
// Create a namespace called 'Article'
namespace Article;
?>

It should be noted that there must be no code before the first namespace in the current script file, and the following methods are all incorrect:

Example 1

// Some logical code is written in front of the script
<?php
$path = "/";
class Comment { }
namespace Article;
?>

Example 2

</html>
<?php
namespace Article;
?>

Why mention the first namespace? Because multiple namespaces can be created in the same script file.

Below, I have created two namespaces and added a Comment class element to each of them:

<?php
// Create a namespace called 'Article'
namespace Article;

// This Comment belongs to the element of the Article space
class Comment { }

// Create a namespace called 'MessageBoard'
namespace MessageBoard;

// This Comment belongs to the element of the MessageBoard space
class Comment { }
?>

You cannot directly call other elements between different spaces, you need to use the namespace syntax:

<?php
namespace Article;
class Comment { }

namespace MessageBoard;
class Comment { }

// Call the Comment class of the current space (MessageBoard)
$comment = new Comment();

// Call the Comment class of the Article space
$article_comment = new \Article\Comment();
?>

It can be seen that when calling the Comment class in the article space in the MessageBoard space, a syntax similar to a file path is used: \space name\element name

In addition to classes, the usage of functions and constants is the same. Below, I have created new elements for the two spaces and output their values in the MessageBoard space.

<?php
namespace Article;

const PATH = '/article';

function getCommentTotal() {
    return 100;
}

class Comment { }

namespace MessageBoard;

const PATH = '/message_board';

function getCommentTotal() {
    return 300;
}

class Comment { }

// Call the constants, functions, and classes of the current space
echo PATH; ///message_board
echo getCommentTotal(); //300
$comment = new Comment();

// Call the constants, functions, and classes of the Article space
echo \Article\PATH; ///article
echo \Article\getCommentTotal(); //100
$article_comment = new \Article\Comment();
?>

Then I indeed got the element data of the Article space.

Subspace

The calling syntax of the namespace is like a file This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation.

Chinese: Use Blog\Article\Comment as Comt; $article_comment = new Comt(); //Conflicts with the Comt in the current namespace, causing a fatal error in the program ?>


### Dynamic Invocation

PHP provides the namespace keyword and the __NAMESPACE__ magic constant for dynamically accessing elements. The __NAMESPACE__ can be dynamically accessed by concatenating strings:


const PATH = '/Blog/article';

class Comment { }

//The namespace keyword represents the current namespace echo namespace\PATH; ///Blog/article $comment = new namespace\Comment();

//The value of the magic constant __NAMESPACE__ is the name of the current namespace echo __NAMESPACE__; //Blog\Article //It can be concatenated into a string and called $comment_class_name = __NAMESPACE__ . '\Comment'; $comment = new $comment_class_name(); ?>


### Issues with String Invocation

In the above example of dynamic invocation, we saw the method of dynamic invocation in the form of a string. If you want to use this method, pay attention to two issues.

**1. Special characters may be escaped when using double quotes**

class name { }

//I want to call Blog\Article\name $class_name = __NAMESPACE__ . "\name"; //But \n will be escaped as a newline character

$name = new $class_name(); //A fatal error occurs ?>


**2. It is not considered a qualified name**

PHP determines the namespace where the element is located and the import situation during the compilation of the script. During the parsing of the script, the string form of the call can only be considered as an unqualified name and a fully qualified name, and it can never be a qualified name.


//Import the Common class use Blog\Article\Common; //I want to call Blog\Article\Common with an unqualified name $common_class_name = 'Common'; //It is actually considered an unqualified name, which means the current namespace's Common class, but I have not created a Common class in the current class $common = new $common_class_name(); //A fatal error occurs: The Common class does not exist

//I want to call Blog\Article\Common with a qualified name $common_class_name = 'Article\Common'; //It is actually considered a fully qualified name, which means the Common class under the Article namespace, but I only defined the Blog\Article namespace, not the Article namespace $common = new $common_class_name(); //A fatal error occurs: The Article\Common class does not exist

namespace Blog\Article;

class Common { } ?> ```

Summary

I have just come into contact with PHP's namespaces and cannot casually give some unpracticed advice. I personally think that the role and function of namespaces are very powerful. If you are writing plugins or general libraries, you no longer have to worry about the problem of name conflicts. However, if a project reaches a certain extent and you want to solve the problem of name conflicts by adding namespaces, I think the workload will not be less than refactoring the names. It also has to be admitted that its syntax will add a certain complexity to the project, so it should be well planned from the beginning of the project and a naming convention should be formulated.

>

Original article link: https://www.cnblogs.com/kuyuecs/p/3556421.html

** Click to share my notes

Cancel

-

-

-

English:

❮ Android Tutorial Touchlistener Ontouchevent Redis Intro Data Structure ❯