php5.3 namespace instructions to help the first contact with namespace Phper Quick understanding

Source: Internet
Author: User
Tags constant definition define function php programming

Namespace one of the most explicit purposes is to solve the problem of duplicate names, PHP does not allow two functions or classes to appear the same name, otherwise it will produce a fatal error. In this case, as long as you avoid naming duplicates can be resolved, the most common way is to contract a prefix, but the method name has become very long, and may still have duplicate names. To avoid this, the namespace is enabled, although it adds a bit of hassle.

The document has a copy of the paragraph: what is a namespace? In a broad sense, namespaces are a way of encapsulating things. This abstract concept can be seen in many places. For example, in an operating system, a directory is used to group related files, and for files in a directory, it plays the role of a namespace. For example, file foo.txt can exist in both directory /home/greg and /home/other , but there cannot be two foo.txt files in the same directory. In addition, when accessing the foo.txt file outside of directory /home/greg , we must place the directory name and directory delimiter before the file name to get /home/greg/foo.txt. The application of this principle to the field of programming is the concept of namespaces.

In PHP, namespaces are used to solve two types of problems encountered when writing a class library or application to create reusable code such as classes or functions:

    • User-written code conflicts with the name of a class/function/constant or third-party class/function/constant inside PHP.
    • Creates an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem), improving the readability of the source code.

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

Take a direct look at an example and slowly understand it.

demo.php content is as follows

namespace DemoNamespace; Class Demo {    private $mysqlHandle;     Public Function __construct () {        echo ' namespace of PHP demo, the demo magic constant ' __namespace__ ' is '. __na mespace__;}    }

  

index.php Code

   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:

    Include ' 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.

Look at a more complicated example.

demo.php File Code

namespace DemoNamespace; Class Demo {    private $mysqlHandle;     Public Function __construct () {        echo ' namespace of PHP demo, the demo magic constant ' __namespace__ ' is '. __na mespace__;}    } 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

    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 , while class internally calls the const constant outside the namespace, class, It can be used just like constants 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" ~

There cannot be any code in front of the first namespace of the current script file, such as the following code that would report a fatal error:

Define ("greeting", "Hello world!"); namespace DemoNamespace; Class Demo {    private $mysqlHandle;     Public Function __construct () {        echo ' namespace of PHP demo, the demo magic constant ' __namespace__ ' is '. __na mespace__;}    } $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"

The class name in the namespace is directly new under the namespace, and 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

Namespace Demotest;class Demo {public    function __construct () {        echo ' This is a test script ';    }} namespace DemoNamespace; Class Demo {    private $mysqlHandle;     Public Function __construct () {        echo ' namespace of PHP demo, the demo magic constant ' __namespace__ ' is '. __na mespace__;}    } $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

This article reprinted from Jingjing's blog ....

php5.3 namespace instructions to help the first contact with namespace Phper Quick understanding

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.