What is a namespace

Source: Internet
Author: User
Tags constant definition naming convention php programming
name SpaceOne of the most clear purposes is to solve the problem of duplicate names, PHP does not allow two functions or classes to appear the same name, or it will produce a fatal error. In this case, as long as you avoid naming duplicates can be resolved, the most common practice 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. Then I might want to add some stats to all of my users ' messages, such as the number of messages I want to get. It is good practice to call them comment the methods provided, but it is obviously not possible to introduce the respective comment classes, and the code will go wrong, and rewriting any of the comment in another place will also reduce maintainability. That's when the class name can only be refactored, and I've contracted a naming convention to precede 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 more code (at least more characters) will be written later when using comment. Furthermore, if you want to add more integration functions to each module, or call each other, the name will need to be reconstructed when the duplicate names occur. Of course, when the project began to notice the problem, and the naming rules can be very good to avoid the problem. Another workaround is to consider using namespaces .

When declaring a namespace , you can include not only variables in the curly brackets, but also the following types:

Variable (can be initialized)

Constant

function (can be defined or declared)

Structural body

Class

Template

Namespaces (namespaces can be defined in a nested definition)

A summary of the use of namespaces :

Tips: The following example becomes two files, a demo.php, a index.php, two files in a sibling directory, a namespace in the demo.php file, and a Demo class, Index.php calls the demo class in demo.php, and the following example shows "output" as the browser accesses index.php.

A simple example

demo.php File Code

<?php  namespace DemoNamespace; class Demo {        private $mysqlHandle;       Public Function construct () {          echo ' namespace of PHP demo, the demo magic Constant ' namespace ' is '. NAMESPACE;      }}? >

index.php File Code

<?php  include ' demo.php ';  Use Demonamespace\demo; $DEMOOBJ = new Demo ();?>

Output 1: "This is namespace by PHP demo, the demo magic Constant" namespace "is DemoNamespace"

Description of the example above: Demo.php has a _namespace magic constant; "It contains a string of the current namespace name. In the global, not included in any namespace code, it contains an empty string. ”

Then do the example:

demo.php do not make changes, change the index.php file, as follows:

<?phpinclude ' demo.php '; $Demo = new Demo ();? >

Output 2: "Fatal error:class ' Demo ' not found in F:\JJserver\demo\index.php on line 4"

This is a common "fatal error" message. According to the usual PHP programming idea, the output here should be consistent with "Output 1", but here it is a fatal error, this is going to freak out? ~

OK, first to solve the problem of the crazy, remove (or comment out) in the demo.php file: "namespace DemoNamespace;" This statement is normal. This is the most common writing method we usually write class and call class, and we don't explain this case of not using namespace.

In contrast to the use of namespace and the two outputs without the use of namespace, and the addition of the definition of namespace to understand, the above fatal error situation is very well understood. Define a namespace in demo.php, that is, after the namespace, then define the demo class, and then the demo class is merged into the DemoNamespace namespace, then to invoke the demo class, it is necessary to call the DemoNamespace namespace first , which is the use of the "Usedemonamespace\demo" statement in the index.php file.

Two, a little more complicated example

demo.php File Code

<?phpnamespace DemoNamespace; Class Demo {    private $mysqlHandle;      Public Function construct () {          echo ' namespace of PHP demo, the demo magic Constant ' namespace ' is '. NAMESPACE;}  }   namespace DemoNameSpace1;   Const Constdefine = ' JJonline1 ';   Class Demo {     private $mysql;   Const Constdefine = ' JJonline2 ';   Public Function construct () {   echo ' the const constant outside class is: '. Constdefine;   Echo ' ===cut-off rule of God!!!! ===';  Echo ' The const constant inside class is: '. self::constdefine;   }? >

index.php File Code

<?php include ' demo.php '; Use Demonamespace1\demo as Test; $Demo = new Test (); Echo ' | | | | '. Demonamespace1\constdefine;? >

Output 3: "The const constant outside class Is:jjonline1===cut-off rule of God!!!! ===the const constant Inside class Is:jjonline2| | | | JJonline1 "

This results in the absence of namespaces, the direct report such as "Fatal Error:cannot Redeclare class Demo" fatal error. But running without an error, which is the benefit of the namespaces introduced later in the php5.3, is the same as in the official explanation cited at the beginning of this article, where files of the same file name under different directories can exist. In the demo.php file, the class class that defines the first name of the demo is merged into the DemoNamespace namespace, and the second name defined as the demo class is merged into the DemoNameSpace1 namespace, so there is no definition of a class that cannot be duplicated. Fatal error. The above writing method is to avoid as far as possible, because the class external const constant name is the same as the const constant name inside the class, it is easy to confuse, here the purpose of writing is to look at the different positional declarations of the const constant, at the time of invocation; output 3 is already obvious, no more ink explanation.

The const constant Constdefine is also presented under the DemoNameSpace1 namespace in demo.php, and it's crazy to get the definition class, because the previous knowledge is define define global constants, and const defines class internal constants; here it is. Play the ... Specifically, no longer explained, the demo.php file code and the results after the operation has been very clear to show the relevant knowledge. The const defined within class can only be called inside class, in the form of Self::constname, and the const constants outside of class are called within class, and can be used directly using constants such as those defined by define. When you need to use a const constant defined outside of class in this namespace, the output in the index.php file is invoked in a way similar to the path.

This example also shows that the use as statement is used in the index.php, See index.php code, meaning at a glance, a class name of new is called Test, but the test class is not defined in demo.php, but there is no error, this is the use as statement, the specific meaning is no longer explained.

With this understanding, the Namespace keyword allows classes that implement various functions to be categorized by specifying different namespaces, and the class under different namespaces can have the same name, and the const constant definition can be raised outside the class. Of course there will be a scope of such a "connotation" ~

Summarize the relevant knowledge of namespace:

1, the current script file in front of the first namespace can not have any code, such as the following code is reported fatal error:

<?phpdefine ("Greeting", "Hello world!"); Namespace Demonamespace;class Demo {private $mysqlHandle; public function construct () {echo ' This is namespace of PHP de Mo, the Demo magic constant "NAMESPACE" is. NAMESPACE; }} $Demo = new Demo ();?>

Running the above code will cause a fatal error: "Fatal error:namespace declaration statement have to is the very first statement in XXXX"

2. The class name in the namespace is directly new under the namespace, you can omit the use syntax, which is caused by the execution of PHP in script order. For example, the following code can be run

<?phpnamespace demotest;class Demo {public    function construct () {        echo ' This is a test script ';    }} Namespa CE demonamespace; Class Demo {    private $mysqlHandle; public function construct () {  Echo's namespace of PHP demo, the demo mag IC constant "NAMESPACE" is. NAMESPACE;}  } $ demo = new demo ();?>

Run result 4: "This is namespace of PHP demo, the demo magic Constant" namespace "is DemoNamespace"

This result shows that, under the same script, the new one does not specify which namespace to use, and then follows the script, using the class in the namespace closest to the new statement

3. Public space: It is easy to understand that methods (functions), class libraries (classes), attributes (variables) that do not have a namespace defined are owned by default to public spaces. This explains why most of the code written for the previous version of PHP5.3.0 is functioning properly in php5.3.0 and above. Also: After a code snippet in a public space is introduced into a namespace, the code snippet in that public space does not belong to any namespace!

The introduction of namespaces, so that PHP object-oriented programming more appropriate, reasonable use of the namespace, you can also let the project file planning, the above is to introduce all the contents of the namespace.

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.