The namespaces in PHP are described in detail

Source: Internet
Author: User
Tags aliases constant exception handling file system php file php code relative require

This article mainly introduces the namespaces in PHP detailed introduction, this article explained the concept of the namespace (namespace), is using the namespace, defines the namespace, the child namespace, calls the code from the namespace and so on content, needs the friend may refer to under

Overview

PHP's support for namespaces has been a difficult journey. Luckily, PHP introduced namespaces starting at 5.3. Since PHP introduced the namespace, the application structure of PHP code has been greatly improved. Many programming languages already have the concept of namespaces, which is a little bit late for PHP support for namespaces, as opposed to other languages. In any case, the introduction of each new feature has its purpose, and, like other languages, PHP introduces namespaces primarily to solve the problem of name collisions.

The concept of namespaces (namespace)

The code is as follows:

When using namespace names in a string, be sure not to forget to escape

You can think of namespaces as a drawer, where you can put pencils, rulers, A4 paper in a drawer, all of which are your own private belongings. Under your drawer is someone else's drawer, others can put the same things in the drawer. In order not to take the wrong items, you decide to put a label on your drawer so that you can see clearly who the item belongs to.

Before, developers had to add underscores in classes, functions, and constants to make their code independent of the code base. This is the equivalent of putting labels on their belongings and placing them in a larger drawer. Although this is also a way to organize your code, this approach is very inefficient.

The advent of namespaces is to solve this problem. We can declare the same functions, classes, and constants in different namespaces without creating a conflict of names. In essence, namespaces are nothing more than a way to mark PHP code hierarchically.

Using namespaces

One thing to be aware of is that we are using namespaces indirectly. Starting with PHP 5.3, all declarations (classes, functions, constants) in a user-defined namespace default to the global namespace.

The global namespace contains definitions for all internal PHP, such as Echo (), Mysqli_connect (), and exception classes. Because the global namespace does not have a separate identity name, it is often used as a global space.

Defining namespaces

The definition of a namespace must be the first statement of the PHP file. The only statement that is allowed to be used before defining a namespace is the Declare statement.

Defining namespaces is simple, and you just need to use the keyword namespace. The name of the namespace needs to follow the naming rules for other identifiers in the PHP file.

The following is an example of defining a namespace:

The code is as follows:

Namespace mynamespace{

Class test{

}

}

If you want to define a block of code that belongs to the global space, you also use the namespace keyword, but the name of the namespace is not followed by the following:

The code is as follows:

namespace {

Class test{

}

}

We can even define multiple namespaces in one file, as follows:

The code is as follows:

  

Namespace MyNamespace {

}

Namespace Mysecondnamespace {

}

namespace {

}

We can also distribute a namespace in separate files, and the handlers that the files contain will automatically merge them. Therefore, restricting a large number of namespaces in the same file is a good programming practice, just as we typically define a separate file for each class.

Copy code code as follows:

One thing to note is that {that contains the namespace code block is optional and can be used or not. In fact, as long as we insist on defining only one namespace in a file, we can completely omit {, which will also make our code look more concise.

Child namespaces

Namespaces can follow a specific level, just like the directory in our computer file system. Child namespaces are especially useful for structuring a project. For example, if your project requires access to the database, you may want to put all database-related code (such as database exception handling) in the same subdirectory.

In order to remain flexible, it is wise to place a child namespace in a subdirectory. This makes your code structure clearer and makes it easier to use the autoloaders that follow the PSR-0 standard.

PHP uses backslashes as delimiters for namespaces, and interestingly, PHP has even considered using a smiley face: as a delimiter for namespaces.

Sub-namespace Definition example:

The code is as follows:

  

Namespace Myprojectdatabase

Class Connection {

}

You can use as many child namespaces as possible:

The code is as follows:

  

namespace Myprojectblogauthhandlersocial;

Class Twitter {

}

One thing to note is that PHP does not support nested definitions of namespaces, and the following code causes a fatal error: Namespace declarations cannot be nested.

The code is as follows:

  

Namespace MyProject {

Namespace Database {

Class Connection {}

}

}

Calling code from a namespace

If you want to instantiate a class in a different namespace, call a function, or use a constant, you need to use a backslash. They can be parsed from three angles:

1. Unqualified name

2. Qualified Name

3. Fully qualified name

Unqualified name (unqualified name)

This is the name of a class, a function, or a constant, but does not include any named references. If namespaces are unfamiliar to you, then this is the angle you are familiar with.

The code is as follows:

  

namespace MyProject;

Class MyClass {

static function Static_method ()

{

Echo ' Hello, world! ';

}

}

unqualified name, resolves to the namespace your are currently in (Myprojectmyclass)

Myclass:static_method ();

Qualified name (qualified name)

This is how we use the child namespaces. Examples are as follows:

The code is as follows:

  

namespace MyProject;

Require ' myproject/database/connection.php ';

Qualified name, instantiating a class from Sub-namespace of MyProject

$connection = new DatabaseConnection ();

Fully qualified name (fully qualified name)

The previously mentioned use of qualified and unqualified names is relative to the namespace currently in place. Both of these methods can only be used to access the current namespace and the deeper level of the child namespace.

If you want to access a higher level than the previous namespace, you need to use the fully qualified name-an absolute path rather than a relative path. This can be attributed to the front of the namespace plus a backslash. Using a fully qualified name lets PHP know that this call starts with global space, not the namespace that is currently in place. Examples are as follows:

The code is as follows:

  

namespace Myprojectdatabase;

Require ' myproject/fileaccess/input.php ';

Trying to access the Myprojectfileaccessinput class

This time it'll work because we use the fully qualified name and note the leading backslash

$input = new Myprojectfileaccessinput ();

For the internal functions of PHP, we do not have to use fully qualified names. In the current namespace, invoke a class or function that does not have an unqualified name, and PHP searches for global space.

With this in mind, we can rewrite the internal functions of PHP as follows:

The code is as follows:

  

namespace MyProject;

Var_dump ($query); Overloaded

Var_dump ($query); Internal

We want to access the global Exception class

The following won't work because there ' no class called Exception in the Myprojectdatabase namespace and Unqualifie D class names don't have a fallback to global spaces

throw new Exception (' Query failed! ');

Instead, we use a single backslash to indicate we want to resolve from global spaces

throw new Exception (' ailed! ');

function Var_dump () {

Echo ' Overloaded global var_dump ()!
';

}

Dynamic invocation

PHP is a dynamic language, and you can use this feature of PHP to invoke namespaces. This is essentially the same as instantiating a variable class and containing a variable file. In a string, the namespace delimiter used by PHP () is also a meta character and therefore needs to be escaped.

The code is as follows:

  

namespace Otherproject;

$project _name = ' MyProject ';

$package _name = ' Database ';

$class _name = ' Connection ';

Include A variable file

Require Strtolower ($project _name. '/'. $package _name. '/' . $class _name). '. php ';

Name of a variable class in a variable namespace. The backslash is escaped to use it properly

$fully _qualified_name = $project _name. '' . $package _name. '' . $class _name;

$connection = new $fully _qualified_name ();

namespace keyword

Keyword namespace is not only used to define a namespace, it can also be used to represent the current namespace, which acts at this time as the Self keyword in the class.

The code is as follows:

  

namespace MyProject;

function Run ()

{

Echo ' Running from a namespace! ';

}

resolves to myprojectrun

Run ();

explicitly resolves to myprojectrun

Namespacerun ();

__namespace__ Constants

Just as the Self keyword cannot represent the name of the current class, the namespace keyword cannot be used to represent the name of the current namespace. The __NAMESPACE__ keyword is used to solve this problem.

The code is as follows:

  

namespace Myprojectdatabase;

' Myprojectdatabase '

Echo __namespace__;

This keyword is useful for determining whether the current code starts from a namespace, and it can also be used to debug code.

Import or Alias

Namespaces in PHP also support imports, and imports are also aliases. Only classes, interfaces, and namespaces can be imported (aliases). Import is a very useful and basic feature in namespaces. It allows us to use an external code package without worrying about the name of the conflict. Import functionality can be implemented using the USE keyword. You can also use the AS keyword to specify an alias when importing.

The code is as follows:

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

A fully qualified name can be replaced with an unqualified alias so that we do not have to use the fully qualified name for each use to simplify the code. The import should be used at the highest level or in the global space of the namespace, and it is illegal to use the import function within a function scope.

The code is as follows:

  

namespace Otherproject;

This holds the Myprojectdatabase namespace and a Connection class in it

Require ' myproject/database/connection.php ';

If we want to access the database connection of MyProject, we are need to use it fully qualified name as we ' re in a differ ENT name space

$connection = new Myprojectdatabaseconnection ();

Import the Connection class (it works exactly the same with interfaces)

Use myprojectdatabaseconnection;

Now this works Too! Before the Connection class is aliased PHP would not have found a otherprojectconnection class

$connection = new Connection ();

Import the Myprojectdatabase namespace

Use Myprojectdatabase;

$connection = new DatabaseConnection ()

We can simplify the above code by using aliases:

The code is as follows:

  

namespace Otherproject;

Require ' myproject/database/connection.php ';

Use myprojectdatabaseconnection as myconnection;

$connection = new MyConnection ();

Use Myprojectdatabase as MyDatabase;

$connection = new Mydatabaseconnection ();

Summarize

Namespaces are used to avoid defining conflicts and introduce a more flexible and organized approach to code. One thing to be aware of is that we are not obligated to use namespaces, which is a way of working with object-oriented. However, if namespaces are used, our code may reach a new level, forcing the grid to look even higher.

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.