Namespaces in PHP details _php tutorial

Source: Internet
Author: User
Tags aliases

Namespaces in PHP are described in detail


This article mainly introduces the namespace details in PHP, this article explains the concept of namespaces (namespace), the use of namespaces, the definition of namespaces, child namespaces, calling code from namespaces, and so on, the need for a friend to refer to the following

Overview

PHP's support for namespaces has gone through a difficult journey. Fortunately, PHP introduced namespaces from 5.3 onwards. Since PHP introduced the namespace, the application structure of PHP code has been greatly improved. Many programming languages have long had the concept of namespaces, and PHP's support for namespaces is a little bit late relative to other languages. In any case, the introduction of each new feature has its purpose, and as in other languages, PHP introduces namespaces primarily to address the problem of name collisions.

The concept of namespaces (namespace)

The code is as follows:

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

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

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

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

Using namespaces

One thing to note is that we are indirectly using namespaces. Starting with PHP 5.3, all declarations (classes, functions, constants) in non-user-defined namespaces are defaulted to the global namespace.

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

Define namespaces

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

Defining namespaces is simple, just 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 is part of the global space, you use the namespace keyword, but the name is not followed by the namespace, as follows:

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 scatter a namespace in different files, and the files contain handlers that will automatically merge them. Therefore, restricting the number of namespaces defined in the same file is a good programming practice, just as we usually define a separate file for each class individually.

Copy the code code as follows:

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

Sub-namespaces

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

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

PHP uses a backslash \ As the delimiter for the namespace, and interestingly, PHP even considered using a smiley face:) as the delimiter for the namespace.

Example of a child namespace definition:

The code is as follows:

  

Namespace Myproject\database

Class Connection {

}

You can use as many sub-namespaces as possible:

The code is as follows:

  

namespace Myproject\blog\auth\handler\social;

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 the 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 names

2. Limited name

3. Fully qualified name

Unqualified name (Unqualified name)

This is the name, function, or constant of a class, but does not include any named references. If the namespace is 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 is currently in (Myproject\myclass)

Myclass:static_method ();

Qualified name (qualified name)

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

The code is as follows:

  

namespace MyProject;

Require ' myproject/database/connection.php ';

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

$connection = new Database\connection ();

Fully qualified name (Fully qualified name)

The previously mentioned use of qualified names and unqualified names is relative to the current namespace. Both of these methods can only be used to access the currently located namespace and a deeper sub-namespace.

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

The code is as follows:

  

namespace 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 ();

For PHP's intrinsic functions, we don't have to use fully qualified names. In the current namespace, calling a class or function that does not exist for an unqualified name, PHP searches the global space.

Remembering this rule, we can rewrite PHP's intrinsic functions 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's no class called Exception in the Myproject\database namespace and Unqualifi Ed class names do not has a fallback to global space

throw new Exception (' Query failed! ');

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

throw new \exception (' ailed! ');

function Var_dump () {

Echo ' Overloaded global var_dump ()!
';

}

Dynamic invocation

PHP is a dynamic language, you can also use this feature of PHP to call the namespace. This is essentially the same as instantiating a variable class and containing a variable file. In the string, PHP uses a namespace delimiter (\) that 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. Note how the backslash are escaped to use it properly

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

$connection = new $fully _qualified_name ();

namespace keywords

The keyword namespace can not only be used to define a namespace, it can also be used to display the current namespace, which at this time is equivalent to the Self keyword in the class.

The code is as follows:

  

namespace MyProject;

function Run ()

{

Echo ' Running from a namespace! ';

}

resolves to myproject\run

Run ();

explicitly resolves to myproject\run

Namespace\run ();

__namespace__ Constants

Just like 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 Myproject\database;

' Myproject\database '

Echo __namespace__;

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

Import or Alias

The namespaces in PHP also support import, and import is also an alias. Only classes, interfaces, and namespaces can be imported (aliases). Import is a very useful and basic feature in namespaces. It allows us to use external code packages without worrying about name collisions. The import function 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 we don't have to use a fully qualified name every time we use it to simplify the code. Imports should be used in the highest or global space of a namespace, and using the Import function within a function scope is an illegal syntax.

The code is as follows:

  

namespace Otherproject;

This holds the Myproject\database namespace with a Connection class in it

Require ' 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 Connection ();

Import the Myproject\database namespace

Use Myproject\database;

$connection = new Database\connection ()

We can simplify the above code by using aliases:

The code is as follows:

  

namespace Otherproject;

Require ' myproject/database/connection.php ';

Use myproject\database\connection as myconnection;

$connection = new MyConnection ();

Use Myproject\database as MyDatabase;

$connection = new Mydatabase\connection ();

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 you use a namespace, our code may reach a new level, forcing the grid to appear taller.

http://www.bkjia.com/PHPjc/1025900.html www.bkjia.com true http://www.bkjia.com/PHPjc/1025900.html techarticle Namespaces in PHP details This article mainly introduces the namespace details in PHP, this article explains the concept of namespaces (namespace), the use of namespaces, the definition of naming ...

  • Related Article

    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.