Namespaces in PHP (namespace) and how to use them

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

Namespace (namespace) in PHP and its use Jianjingjing 2 years ago (2014-01-02) 8,495 views phpphp since 5.3.0, a namespace keyword was introduced and __namespace__ Magic Constants (Of course the Use keyword or use as nested statements are also introduced); So what is a namespace? PHP website has been clearly defined and visualized interpretation, here directly from the PHP website copy a paragraph of text [source]. "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. "At present, the php5.5 series has been introduced, the object-oriented programming of PHP is also gradually improved, and this article to learn the namespace keyword is to solve the PHP object-oriented programming process has appeared in various" trouble ", the specific trouble is as follows: 1, User-written code conflicts with the name of a class/function/constant or third-party class/function/constant inside PHP. 2, in order to alleviate the trouble 1, usually write various classes will use a longer class name or to implement different functions of the class to add a name prefix (or suffix). 3, do not use the Magic function __autoload case, and each class and the exclusive PHP file, in order to invoke a different class, More include (or require or require_once) statements are written at the beginning of another PHP file that uses these classes. ============ the use of namespaces: tips: The following example becomes two files, A demo.php, a index.php, two files in the same sibling directory, the demo.php file to write the namespace and the demo class, index.php call the demo class in demo.php, the following example "output" That means 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 '. __namesp ace__; }}?>index.php file code <?php include ' demo.php '; Use Demonamespace\demo; $DEMOOBJ = new Demo ();? > Output 1: "This is namespace for PHP demo, the demo magic Constant" __namespace__ "is DemoNamespace" description of the above example: Demo.php has a _na Mespace__ a 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 change, change the index.php file, as follows: <?php 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 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 , i.e. in IThe "Use Demonamespace\demo" statement is used in the ndex.php file.  Two, a little more complicated 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 '. __namesp ace__; }} 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 namespaces introduced after php5.3, is a file with the same file name in a different directory as the official explanation referenced at the beginning of this articleCan exist just as a reason. 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: <?php define ("greeting", "Hello World! ");  namespace DemoNamespace;  Class Demo {private $mysqlHandle; PubliC function __construct () {echo ' This is namespace of PHP demo, the demo magic constant ' __namespace__ ' is '. __namespace__ ; }} $Demo = new Demo ();? > Run the above code, a fatal error occurs: "Fatal error:namespace declaration statement have to is the very first statement in XXXX" 2, the name space directly under the new life Class name in the namespace, you can omit the use syntax, which is caused by the execution of PHP in script order. For example the following code is possible to run <?php 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 '. __namesp ace__; }} $Demo = new Demo ();? > Run result 4: "This is namespace of PHP demo, the demo magic Constant" __namespace__ "was demonamespace" This result shows that the same script under the new one does not specify US E which namespace, along the script, uses the CLASS3, public space in one of the namespaces closest to the new statement: It is easy to understand that methods (functions) that do not define namespaces, class libraries (classes), and attributes (variables) 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! Public space this piece, or you write code better. 4, as the directory structure,Namespaces also have the concept of sub-namespaces, which are no longer illustrative. The introduction of namespaces, so that PHP object-oriented programming more appropriate, reasonable use of namespaces, but also for project file planning, each class library planning more reasonable, easy to read. More questions about php5.3.0 and the namespaces introduced above are no longer covered. Reprint please specify the title and link of this article: "Namespace in PHP (namespace) and its use in detail"

  

Namespaces in PHP (namespace) and how to use them

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.