A detailed introduction to the new feature namespaces in PHP

Source: Internet
Author: User
Tags aliases constant php class php file php code zend zend framework

1. What is a namespace

If you only need to know one of the modern PHP features, it should be a namespace. Namespaces are introduced in PHP5.3.0 to organize PHP code in a virtual hierarchy similar to the directory structure of file systems in the operating system. Namespaces are the foundation of modern PHP component ecology, and modern PHP component framework code is placed in its own globally unique vendor namespace to avoid conflicts with common class names used by other vendors.

Let me take a look at how the real PHP component uses namespaces. HTTP components in the Laravel framework are used to manage HTTP requests and responses, and this component uses common class names, such as request, Response, and many other PHP components that use the same class name, since other PHP code uses the same class name. So how do you use this component? In fact, we can use it safely because the code for this component is placed in the unique vendor namespace illuminate. Open the Warehouse (https://github.com/laravel/framework/blob/master/src/Illuminate/Http/Response.php) for this component in GitHub and locate the response.php file:

The 3rd line of code is as follows:

namespace Illuminate\http;
This line is a PHP namespace declaration statement, and the code declaring the namespace should always be placed on the first line after the <?php tag. Through the declaration statements of this namespace we can see that response is in the vendor namespace illuminate (the topmost namespace) and we see that the response class is in the child namespace HTTP, You can look at the other files at the same level as the response.php file and find that they all use the same namespace declaration statement.

The role of namespaces is to encapsulate and organize related PHP classes, just like placing related files in the same directory in a file system. Unlike the physical file system of the PHP namespace and the operating system, this is a virtual concept that is not necessarily the same as the directory structure in the file system, but most PHP components, in order to be compatible with the widely used PSR-4 automatic loading standard, place namespaces in the subdirectory of the corresponding file system.

2. Why use namespaces
As mentioned earlier, our code may use the same class name, interface name, function, or constant name as other developers ' code, and if the namespace is not used, the name will collide, causing PHP to perform an error. Instead of using namespaces to place code in a unique vendor namespace, our code can use the same class name, interface name, function, or constant name as other developers.

Of course, if you're developing a small personal project, with a small amount of dependency, a class name conflict may not be a problem, but if you work on a team and develop large projects that are used by many third-party dependencies, you need to take the naming conflict seriously because you cannot control how the project relies on classes, interfaces, functions, and constants that are introduced in the global namespace. That's why you use namespaces.

3. Declaring namespaces
Each PHP class, interface, function, and constant is in the namespace, and declaring the namespace is simple, the first line after the <?php tag declares that the statement begins with a namespace, followed by a space, then the name of the namespace, and then the end.

Namespaces are often used to set top-level vendor names, such as we set the vendor name to Laravelacademy:

<?php
namespace Laravelacademy;
All PHP classes, interfaces, functions, and constants declared after this namespace declaration statement are in the Laravelacademy namespace and have some relationship with Laravel College. What should we do if we want to organize the code used by the college? The answer is to use a child namespace.

The child namespace is declared exactly the same as the previous example, the only difference being that we use the \ symbol to separate the namespace from the child namespace, for example:

<?php
namespace laravelacademy\modernphp;
All the classes, interfaces, functions, and constants after this namespace are located in laravelacademy\modernphp.

Classes in the same namespace need not be declared in the same PHP file, you can specify a namespace or a child namespace at the top of the PHP file, and the code for that file is part of that namespace or child namespace. So we can write multiple classes that belong to the same namespace in different files.

Note: The vendor namespace is the topmost namespace and the most important namespace for identifying a brand or organization that must be globally unique. Child namespaces are relatively less important, but they can be used to organize your project's code.
4, Import and Alias
Prior to the advent of namespaces, PHP developers used Zend-style class names to resolve naming conflicts, a class naming scheme that was popular with the Zend Framework, which uses an underscore in the PHP class name to represent the file system's directory separator. This Convention has two functions: first, to ensure that the class name is unique; second, the native loader replaces the underscore in the class name with the file system's directory separator, which determines the path to the file. For example, the Zend_cloud_documentservice_adapter_windowsazure_query class corresponds to a file that is Zend/cloud/documentservice/adapter/windowsazure /query.php. As you can see, this naming has a disadvantage: the class name is particularly long.

Modern PHP namespaces also have this problem, such as the full full name of the Response class above is illuminate\http\response, fortunately, we can change this situation by importing and creating aliases.

Import means that in each php file you tell php which namespace, class, interface, function, and constant you want to use, and you don't need to use the full name when you import it:

<?php
Use Illuminate\http\response;

$response = new Response (' Oops ', 400);
$response->send ();
We used the USE keyword to tell PHP that we want to work with the Illuminate\http\response class, we just need to enter a fully qualified class name, and then instantiate the response without using the full class name.

If you think that the class name is still long, you can create an alias. Creating aliases refers to telling PHP that I want to use a simple name to refer to imported classes, interfaces, functions, or constants:

<?php

Use Illuminate\http\response as Res;

$res = new Res (' Oops ', 400);
$res->send ();
You can also import functions and constants from PHP 5.6, but to adjust the syntax of the USE keyword, if you want to import a function, you need to Func:

<?php
Use func namespace\functionname

FunctionName ();
If you want to import constants, you can use constant:

<?php
Use constant namespace\const_name;

Echo const_name;
Aliases, of course, are created as well as classes.

5. Practical Skills
Multiple Import

If you want to import multiple classes, interfaces, functions, or constants in a PHP file, you need to use more than one usage statement at the top of the php file, and PHP supports writing multiple use statements in a single line with short syntax:

<?php
Use Illuminate\http\request,
Illuminate\http\response;
However, for readability, it is not advisable to write this, or a line to write a use statement is better:

<?php
Use Illuminate\http\request;
Use Illuminate\http\response;
A file uses multiple namespaces

PHP allows you to define multiple namespaces in one file:

<?php
Namespace Foo {
Declaring classes, interfaces, functions, constants
}

Namespace Bar {
Declaring classes, interfaces, functions, constants
}
But doing so badly violates the good practice of "one document A class" and is therefore not recommended.

Global namespaces

If the referenced classes, interfaces, functions, and constants do not specify a namespace, PHP assumes that the referenced classes, interfaces, functions, and constants are in the current namespace. If you want to use a class, interface, function, or constant of another namespace, you need to use the fully qualified PHP class name (namespace + class name).

Some code is in the global namespace, there is no namespace, such as the native exception class. When referencing global code in a namespace, you need to add a symbol before a class, interface, function, or constant:

<?php
namespace My\app;

Class Foo {
Public Function dosomething () {
throw new \exception ();
}
}
Auto Load

Namespaces also provide a solid foundation for the PSR-4 automatic loading standard developed by Php-fig, which is used by most modern PHP components, and relies on composer to automatically load dependencies on projects. We will also introduce composer and php-fig in detail, and now you just need to know that there is no namespace, there is no modern PHP ecosystem and a new component-based architecture, this shows the importance of namespaces.

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.