Namespacing in PHP (using Namespaces in PHP)

Source: Internet
Author: User
Tags naming convention php script

  Recently learn PHP namespace, Chinese documents are not many, search for an English, speak of the system, I would like to translate, for later review, we have any ideas or more profound or more understanding of the views hope to be generous, the younger generation grateful.

Original: http://code.tutsplus.com/tutorials/namespacing-in-php--net-27203

About PHP's support for namespaces has gone through a rough journey. Thankfully, from PHP5.3 onwards, added a pair of namespaces. PHP's code structure has thus improved a lot. But how exactly should we use namespaces?

First, what is a namespace

 "Stop playing. To remove the preceding backslash, when you store a namespace in a string variable. ”

Think of the namespace as a drawer in which you can put all kinds of things: think of a pencil, a piece of paper, and so on, these are your things. Under your drawer is someone else's drawer, and he can put all kinds of things in his drawer. In order to avoid the wrong side of each other's things, you decide to label the drawer, so it is clear which drawer type belongs to whom.

Previously, when namespaces were not introduced, developers used the underscore "_" in their classes, functions, and constants to distinguish between them. This is tantamount to labeling individual items and putting them in the same large drawer. Of course, this is at least a bit of a structure, not so messy, but it's not very efficient.

Namespaces can save all this. You can define functions, classes, interfaces, and constants of the same name within each namespace, so long as they are in different namespaces, this will not be an error. Essentially, a namespace is just a hierarchy of things that identify regular blocks of PHP code.

  "You're already using namespaces."

It's important for you to remember that you are indirectly using namespaces, php5.3, all code definitions, if no display definitions are in the user-named namespace, are defined in a global namespace by default. The global namespace also contains many of the built-in function definitions for PHP, like Echo (), mysql_connect (), and Exception class. Because the global namespace does not have a separate identity name, it usually refers to the global space.

Remember, you don't have to be sure to use namespaces. Your PHP script can also perform well even without namespaces, and joining namespaces may not happen too quickly.

Second, how to define a namespace

In a php file, the definition of a namespace should be one of the first declarations (the PHP interpreter should have encountered it). Note: The only thing that can be declared before declaring a namespace is the declare declaration, only when declare declares the encoding of the script file.

Declaring a namespace is a simple namespace keyword, and the name of the namespace is the same as the naming convention for other identifiers in PHP. It can only have letters, numbers, underscores, and cannot start with a number.

<?php namespace MyProject {    //Regular PHP code goes here, anything goes!    function run ()     {        echo ' Running from a namespace! ';    }}

If you want to assign a block of code to the global space, you use the namespace keyword, but you don't have a name behind it.

If you want to assign a code block to the global space, you use the namespace keyword without appending a name.

<?phpnamespace{  //global space!  }

You can define multiple namespaces in the same file.

<?phpnamespace myproject{  //  }namespace mysecondproject{  //  }namespace {  //  }

You can also use the same namespace in multiple files, and the file's inclusion process will automatically merge them. Therefore, a good programming practice is to use only one namespace per file, just as you would define a class in just one file.

  Namespaces are used to avoid naming (defining) conflicts, and to get more flexibility to organize your code better.

Note that the namespace used to surround the code block curly braces "{}" is completely optional and you can not do it. In fact, stick to the principle of a file namespace, and then omit the curly braces to make your code much more concise-no need for code indentation, code nesting.

Sub-namespaces

Namespaces can follow a certain level (level), just like the directory structure in your computer's file system. Child namespaces are very useful for organizing your code structure. For example, if your project requires access to a database, you might want to put all the database-related code, such as database exceptions and link handles, in a sub-namespace called database.

In order to maintain flexibility, it is advisable to place a sub-namespace in a subdirectory. This has prompted your code to be more structured and easier to load automatically using Autoloader. PHP uses a backslash "\" as the delimiter for the namespace.

myproject/database/connection.php<?php namespace Myproject\database class Connection {    //handling database Connections

You can use a lot of sub-namespaces as long as you like

<?php namespace Myproject\blog\auth\handler\social; Class Twitter {    //Handles Twitter authentification}

It is not supported to define nested sub-namespaces. The following example throws a serious error "namespace declaration cannot be nested!" ”。

<?phpnamespace MyProject {    namespace Database {        class Connection {}}}    
Iii. calling code within a namespace

If you instantiate an object in a different namespace, or call a function, or use a constant, you want to use the syntax of a backslash. They can be resolved in the following three ways.

    • Non-restricted name
    • Name of the restriction
    • Full-throttle Name

(1) Non-restricted name

This is the name of a class, the name of the function, or the name of the constant, and does not contain a reference to any of the namespaces. If you are just touching namespaces, this is the way you often use them.

<?phpnamespace MyProject; Class MyClass {    static function Static_method ()    {        echo ' Hello, world! ';    }}//Unqualified name, resolves To the namespace is currently in (Myproject\myclass) Myclass:static_method ()

(2) Name of the restriction

This is how we access the sub-namespace hierarchy, which uses the backslash syntax.

<?phpnamespace MyProject; Require ' myproject/database/connection.php '; Qualified name, instantiating a class from a sub-namespace of myproject$connection = new Database\connection ();

The following example throws a serious error: "Fatal error:class ' myproject\database\myproject\fileaccess\input ' not found".

This is because Myproject\fileaccess\input access is relative to the namespace you are currently in.

<?phpnamespace myproject\database; Require ' myproject/fileaccess/input.php '; Trying to access the myproject\fileaccess\input class$input = new Myproject\fileaccess\input ()

(3) Fully-restricted namespaces 

Both the unrestricted namespace and the restricted namespace are relative paths relative to the namespace-----you are currently located in. They are only used to access their same level or child namespaces.

If you want to access a function, class, or constant, and they are in a higher level namespace, you will use a fully restricted namespace----absolute path instead of relative path. This needs to precede your call with a backslash "\". This will let PHP know that the call will start from the global space to parse instead of the relative path.

<?phpnamespace myproject\database; Require ' myproject/fileaccess/input.php ';  Trying to access the Myproject\fileaccess\input class//this time it'll work because we use the fully qualified name, Note the leading backslash$input = new \myproject\fileaccess\input ();

There is no requirement to use a fully restricted name within a PHP function, to invoke a constant or function that does not exist with the current namespace by an unrestricted name, and PHP will automatically go to the global space to look for them. This is a built-in backward lookup, but this does not apply to calling the class without restricting the name (that is, PHP does not automatically go to the global space when calling a class that doesn't exist with the current namespace without restricting the name). Keeping this in mind, we can now reload the internal PHP function and still call the original function (or constant).

<?phpnamespace MyProject; Var_dump ($query); Overloaded\var_dump ($query); Internal//We want to access the global Exception class//the following won't work because there ' s no class called Exception in the Myproject\database namespace and unqualified class names does not has a fallback to global space//throw n EW Exception (' Query failed! '); Instead, we use a single backslash to indicate we want to resolve from global Spacethrow new \exception (' ailed! '); function Var_dump () {    echo ' Overloaded global var_dump ()!<br/> '
}

Dynamic invocation

PHP is a dynamic programming language, so it is also possible to apply this function to a call on a namespace. This is essentially analogous to instantiating a variable class or including a variable file. The delimiter for the PHP namespace is also a meta-character. Don't forget to remove the front backslash when you store the namespace in an automatic string variable.

<?phpnamespace Otherproject; $project _name = ' MyProject '; $package _name = ' Database '; $class _name = ' Connection '; Include a variable filerequire strtolower ($project _name. ‘/‘. $package _name.  ' /‘ . $class _name). '. php '; Name of a variable class in a variable namespace. Note how the backslash are escaped to use it properly$fully_qualified_name = $project _name. ‘\\‘ . $package _name. ‘\\‘ . $class _name; $connection = new $fully _qualified_name ();
Four, namespace key words

The namespace keyword is not only used to define a namespace, it can also be used to parse the current namespace, functionally similar to the keyword self in a class.

<?phpnamespace MyProject; function run () {    echo ' Running from a namespace! ',}//resolves to myproject\runrun (),//explicitly resolves to MyProj Ect\runnamespace\run ();
V, __namespace_ constants

Much like the Self keyword, which cannot be used to determine which class the current class is in, nor can the NAMESPACE keyword be used to determine what namespace the current namespace is, which is why we use the __NAMESPACE__ constant.

<?phpnamespace myproject\database; ' Myproject\database ' echo __namespace__;

This constant is very useful, and if you are just starting to learn the namespace, it is also helpful for debugging. As a string, it can also be used in dynamic code calls, as we have said before.

Six, alias or import

"No need to use namespaces"

Namespaces in PHP support importing importing. Import is also called an alias. Only classes, interfaces, namespaces can be aliased or imported.

Importing is very useful and is a very important aspect of namespaces. It gives you the ability to use external package code, like a class library, without worrying about naming conflicts. Imports are supported by using the USE keyword. Develop a custom alias followed by the AS keyword.

Use [Name of class, interface or namespace] as [Optional_custom_alias]

How does the import happen?  

How does it ' s done

A fully restricted name can take a short, unrestricted name, so you don't have to write a long, full-restricted name every time you want to use it. Aliases or imports should occur (or be called used) at the highest level of scope or in global space. Try to use an illegal (non-grammatical) import in a method or scope of a function.

<?phpnamespace Otherproject; This holds the Myproject\database namespace with a Connection class in Itrequire ' myproject/database/connection.php '; If we want to access the database connection of MyProject, we need to use it fully qualified name as we ' re in a differ ent name space$connection = new \myproject\database\connection (); Import the Connection class (it works exactly the same with interfaces) use Myproject\database\connection; Now this works Too! Before the Connection class is aliased PHP would not has found an otherproject\connection class$connection = new Connect Ion (); Import the myproject\database namespaceuse myproject\database; $connection = new Database\connection ()

Alternatively, you can take a different name as an alias.

<?phpnamespace Otherproject; Require ' myproject/database/connection.php '; Use myproject\database\connection as myconnection; $connection = new MyConnection (); Use Myproject\database as MyDatabase; $connection = new Mydatabase\connection ();

You can also allow importing global classes like the exception class. When you import it, you can no longer write his long, full-restricted name.

Note that the imported name is not resolved to a path relative to the current namespace, but rather an absolute path, starting with the entire zone space. This means that leading backslash payments are unnecessary and not recommended.

<?phpnamespace MyProject; Fatal error:class ' someproject\exception ' not foundthrow new Exception (' an exception! '); Ok!throw New \exception (' an exception! '); Import Global Exception. ' Exception ' is resolved from a absolute standpoint, the leading backslash is unnecessaryuse Exception; Ok!throw New Exception (' an exception! ');

Although the code for namespaces can be dynamically invoked, dynamic import is not supported.

<?phpnamespace Otherproject; $parser = ' markdown '; This is valid Phprequire ' myproject/blog/parser/'. $parser. '. php '; This is Notuse myproject\blog\parser\ $parser;
Conclusion

Namespaces are used to avoid defining conflicts and introduce more flexibility to better organize your code. Remember that you don't have to say you need to use namespaces. It is used in conjunction with object-oriented workflows that are common. However, hopefully, you will consider bringing your PHP project to the next level by using namespaces. Have you decided to do this?

Namespacing in PHP (using Namespaces in PHP)

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.