The use of the PHP namespace (Namespace) is detailed ____php

Source: Internet
Author: User
Tags aliases naming convention php and php script

Namespace one of the most explicit purpose is to solve the problem of duplicate name, PHP does not allow two functions or classes appear the same names, otherwise a fatal error will occur. In this case, just avoid naming duplicates to resolve

For namespaces, the official documentation has been very detailed [view], and I've done some practice and summary here.

Namespace one of the most explicit purpose is to solve the problem of duplicate name, PHP does not allow two functions or classes appear the same names, otherwise a fatal error will occur. In this case, if you avoid naming duplicates, the most common approach is to contract a prefix.

Example: There are two modules in the project: article and Message board, each of which has a class comment that handles user messages. After that, I might want to add some stats to all the users ' messages, for example, I want to get the number of messages. It's a good idea to call them comment, but it's not easy to introduce your own comment class at the same time, the code can go wrong and rewriting any one of the comment in another place can also degrade maintainability. Then you can only refactor the class name, I have agreed to a naming convention, in front of the class name with the module name, like this: Article_comment, messageboard_comment

As you can see, the name becomes very long, which means that when you use comment later, you will write more code (at least more characters). Moreover, if you want to add some more integration functions to each module, or call each other, the name will need to be reconstructed when duplicate names occur. Of course, the problem is noticed at the beginning of the project, and naming rules can be a good escape from this problem. Another workaround might consider using namespaces.


Note:

Constants mentioned in this article: the PHP5.3 start const keyword can be used outside of a class. Both const and define are used to declare constants (their differences are not detailed), but in namespaces the role of the define is global, while the const acts on the current space. The constants I refer to in the article refer to constants declared using Const.


Basis
Namespaces divide code into different spaces (regions), constants, functions, classes in each space (to be lazy, what I call the elements below) do not affect each other, a bit like the "encapsulation" concept we often refer to.

Creating a namespace requires the use of the namespace keyword, so that:
Copy code code as follows:
<?php

Create a namespace named ' Article '
namespace Article;

?>

Note that there is no code in front of the first namespace of the current script file, and the following is the wrong syntax:
Copy code code as follows:
Example One
Wrote some logical code in front of the script

<?php

$path = "/";

Class Comment {}

namespace Article;

?>

Case II
Some characters were printed before the script

<?php

namespace Article;

?>

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

I created two namespaces below, and added a comment class element to each of these two spaces:
Copy code code as follows:
<?php

Create a namespace named ' Article '
namespace Article;

This comment is an element of article space
Class Comment {}


Create a namespace named ' Messageboard '
namespace Messageboard;

This comment is an element of messageboard space
Class Comment {}
?>

You cannot call other elements directly between different spaces, and you need to use the syntax of the namespace:
Copy code code as follows:
<?php

namespace Article;

Class Comment {}


namespace Messageboard;

Class Comment {}

Call the comment class for the current space (messageboard)
$comment = new comment ();

Call comment class for article space
$article _comment = new \article\comment ();

?>

You can see that when you call the comment class in article space in messageboard space, you use a syntax like a file path: \ space name \ element name

In addition to classes, the use of functions and constants is the same, I created new elements for two spaces, and output their values in the messageboard space.
Copy code code as follows:
<?php

namespace Article;

Const PATH = '/article ';

function Getcommenttotal () {
return 100;
}

Class Comment {}


namespace Messageboard;

Const PATH = '/message_board ';

function Getcommenttotal () {
return 300;
}

Class Comment {}

constants, functions, and classes that call the current space
Echo PATH; Message_board
Echo Getcommenttotal (); 300
$comment = new comment ();

Calling constants, functions, and classes in article space
Echo \article\path; Article
Echo \article\getcommenttotal (); 100
$article _comment = new \article\comment ();

?>

Then I did get the element data for the article space.


Child space
The invocation syntax of namespaces makes sense as a file path, allowing us to customize the subspace to describe the relationships between the spaces.

Sorry I forgot to say, article and message board these two modules are in fact in the same blog project. If you use namespaces to express their relationships, this is true:
Copy code code as follows:
<?php

I use this namespace to represent the article module under the blog
namespace Blog\article;

Class Comment {}


I use such namespaces to represent the message board module under the blog
namespace Blog\messageboard;

Class Comment {}

Class that calls the current space
$comment = new comment ();

Calling a class of blog\article space
$article _comment = new \blog\article\comment ();

?>

Also, subspace can define many levels, such as Blog\article\archives\date


Public space
I have a common_inc.php script file that has some handy functions and classes:
Copy code code as follows:
<?php

function GetIP () {}

Class Filterxss {}

?>

This script is introduced into a namespace, and the elements in the script do not belong to that namespace. If no other namespace is defined in this script, its elements are always in the public space:
Copy code code as follows:
<?php

namespace Blog\article;

Introducing script files
Include './common_inc.php ';

$filter _XSS = new FILTERXSS (); Fatal error occurred: BLOG\ARTICLE\FILTERXSS class not found

$filter _XSS = new \FILTERXSS (); That's right

?>

The way to call a public space is to add it directly to the element name, or else the PHP parser will think I want to invoke the element in the current space. In addition to the custom element, also includes the PHP to bring the element, all belongs to the public space.

To mention, the functions and constants of the public space can be called normally without adding \ (I don't understand why PHP does this), but in order to properly differentiate between elements, it is recommended that you call the function by adding \


Name terminology
Before you say alias and import, you need to know the terms for space three names and how PHP parses them. The official document is very good and I'll just get it.

1. Unqualified name, or class name that does not contain a prefix, such as $comment = new Comment ();. If the current namespace is blog\article,comment, it will be resolved to blog\article\comment. If the code that uses comment is not contained in code in any namespace (in global space), then comment is resolved to comment.

2. A qualified name, or a name that contains a prefix, such as $comment = new Article\comment ();. If the current namespace is a blog, then Comment is resolved to blog\article\comment. If the code that uses comment is not contained in code in any namespace (in global space), then comment is resolved to comment.

3. Fully qualified name, or contains the name of the global prefix operator, such as $comment = new \article\comment ();. In this case, Comment is always resolved to the literal name (literal name) article\comment in the code.

You can actually compare these three names to file names (such as comment.php), relative path names (such as./article/comment.php), Absolute pathname (for example,/blog/article/comment.php), which may be easier to understand.

I have used several examples to represent them:
Copy code code as follows:
<?php

Create a Space blog
namespace Blog;

Class Comment {}

Unqualified name that represents the current blog space
This call will be parsed into blog\comment ();
$blog _comment = new comment ();

Qualified names, representing the relative to the blog space
This call will be parsed into blog\article\comment ();
$article _comment = new Article\comment (); Class is not preceded by a backslash \

Fully qualified name, representing absolute in blog space
This call will be parsed into blog\comment ();
$article _comment = new \blog\comment (); Class is preceded by a back ramp bar \

Fully qualified name, representing absolute in blog space
This call will be parsed into blog\article\comment ();
$article _comment = new \blog\article\comment (); Class is preceded by a back ramp bar \


Create a child space for a blog article
namespace Blog\article;

Class Comment {}

?>

In fact, I've been using unqualified names and fully qualified names, and now they can finally name them.


Aliases and imports
Aliases and imports can be seen as a quick way to invoke namespace elements. PHP does not support import functions or constants.

They are implemented by using the use operator:
Copy code code as follows:
<?php

namespace Blog\article;

Class Comment {}


Create a BBS space (I have a plan to open a forum)
namespace BBS;

Import a Namespace
Use blog\article;
To invoke an element with a qualified name after importing the namespace
$article _comment = new Article\comment ();

Use aliases for namespaces
Use blog\article as Arte;
Use aliases instead of space names
$article _comment = new Arte\comment ();

Import a class
Use blog\article\comment;
You can invoke an element with an unqualified name after importing a class
$article _comment = new comment ();

Using Aliases for classes
Use blog\article\comment as COMT;
Use aliases instead of space names
$article _comment = new COMT ();

?>

I noticed how the current space would have the same name element if the element was imported. Obviously, the result will be a fatal error.

Cases:
Copy code code as follows:
<?php

namespace Blog\article;

Class Comment {}


namespace BBS;

Class Comment {}

Class COMT {}


Import a class
Use blog\article\comment;
$article _comment = new comment (); Comment Conflict with current space, program generates fatal error

Using Aliases for classes
Use blog\article\comment as COMT;
$article _comment = new COMT (); COMT conflict with current space, program generates fatal error

?>

Dynamic invocation
PHP provides dynamic access to NAMESPACE keywords and __namespace__ Magic constants, __namespace__ can be dynamically accessed by combining strings:
Copy code code as follows:
<?php

namespace Blog\article;

Const PATH = '/blog/article ';

Class Comment {}


The namespace keyword represents the current space
Echo Namespace\path; Blog/article
$comment = new Namespace\comment ();

Magic constant __namespace__ value is the current space name
Echo __namespace__; Blog\article
Can be grouped into strings and called
$comment _class_name = __namespace__. ' \comment ';
$comment = new $comment _class_name ();

?>

The problem is called in string form

In the example of the dynamic invocation above, we see a dynamic invocation of the string as a way to pay attention to two problems if you want to use this method.

1. Special characters may be escaped when using double quotes
Copy code code as follows:
<?php

namespace Blog\article;

Class Name {}

I was trying to call Blog\article\name.
$class _name = __namespace__. "\name"; But \ nthe will be escaped as a newline character.

$name = new $class _name (); Fatal error occurred

?>

2. Not considered a qualified name

PHP determines the space in which the elements are located and how they are imported when the script is compiled. When parsing a script, a string invocation can only be considered a unqualified name and a fully qualified name, and can never be a qualified name.
Copy code code as follows:
<?php

namespace Blog;

Import Common class
Use Blog\article\common;
I want to invoke Blog\article\common with an unqualified name
$common _class_name = ' common ';
is actually treated as an unqualified name and represents the common class of the current space, but my current class does not create a common class
$common = new $common _class_name (); Fatal error occurred: Common class does not exist

I want to invoke Blog\article\common with a qualified name
$common _class_name = ' Article\common ';
is actually treated as a fully qualified name and represents the common class under the article space, but I only define the blog\article space instead of the article space below
$common = new $common _class_name (); Fatal error occurred: Article\common class does not exist


namespace Blog\article;

Class Common {}

?>

Summary
I have just contacted the namespace of PHP and can't give some suggestions without practice. I personally think that the role and function of the namespace is very powerful, if you want to write plug-ins or general library when no longer need to worry about the name of the problem. However, if the project is to a certain extent, by adding namespaces to solve the duplicate name problem, I feel that the workload will not be the proportion of small names. Also have to admit that its syntax will add a certain degree of complexity to the project, so from the beginning of the project should be good planning it, and develop a naming convention.

PS: from the script home

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.