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)
Copy Code code 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:
Copy Code code 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:
Copy Code code as follows:
namespace {
Class test{
}
}
We can even define multiple namespaces in one file, as follows:
Copy Code code as follows:
<?php
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 a backslash \ as a namespace delimiter, and interestingly, PHP even considered using a smiley face: as a namespace separator.
Sub-namespace Definition example:
Copy Code code as follows:
<?php
Namespace Myproject\database
Class Connection {
}
You can use as many child namespaces as possible:
Copy Code code as follows:
<?php
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.
Copy Code code as follows:
<?php
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.
Copy Code code as follows:
<?php
namespace MyProject;
Class MyClass {
static function Static_method ()
{
Echo ' Hello, world! ';
}
}
unqualified name, resolves to the namespace your are currently in (Myproject\myclass)
Myclass:static_method ();
Qualified name (qualified name)
This is how we use the child namespaces. Examples are as follows:
Copy Code code as follows:
<?php
namespace MyProject;
Require ' myproject/database/connection.php ';
Qualified name, instantiating a class from Sub-namespace of MyProject
$connection = new Database\connection ();
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 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:
Copy Code code as follows:
<?php
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 and note the leading backslash
$input = new \myproject\fileaccess\input ();
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:
Copy Code code as follows:
<?php
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 Myproject\database namespace and Unqualifi Ed 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 ()!<br/> ';
}
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.
Copy Code code as follows:
<?php
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.
Copy Code code as follows:
<?php
namespace MyProject;
function Run ()
{
Echo ' Running from a namespace! ';
}
resolves to myproject\run
Run ();
explicitly resolves to myproject\run
Namespace\run ();
__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.
Copy Code code as follows:
<?php
namespace Myproject\database;
' Myproject\database '
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.
Copy Code code 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.
Copy Code code as follows:
<?php
namespace Otherproject;
This holds the Myproject\database 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 \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 have found a 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:
Copy Code code as follows:
<?php
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 namespaces are used, our code may reach a new level, forcing the grid to look even higher.