Home > Article > Backend Development > How to define space in php namespace?
This article will begin to introduce namespaces. Namespaces are a way of encapsulating things, and this abstract concept can be seen in many places. Today we will introduce it, you can refer to it if you need it.
First, let’s understand what a namespace is. (If necessary, please refer to PHP Namespace)
In PHP, namespace can solve the problem of writing class libraries or applications (such as classes or functions) and creating reusable code. Problems encountered:
The name of the code written by the user conflicts with the name of the class/function/constant in PHP or the name of the third-party class/function/constant.
Create an alias (or abbreviation) for a long user-written identifier name to improve source code readability.
PHP's namespace provides a way to group related classes, functions, and constants together.
Now let us officially enter today’s introduction, how to define a namespace.
First let’s look at a little chestnut.
<?php declare(encoding='UTF-8'); //定义多个命名空间和不包含在命名空间中的代码 namespace MyProject { const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } } namespace { // 全局代码 session_start(); $a = MyProject\connect(); echo MyProject\Connection::start(); } ?>
We observed and found that these two pieces of code have a common feature, that is, the keyword "namespace
", but the keywords are different. What is the reason? We will know it after we learn about namespaces.
By default, all constant, class, and function names are placed in the global space, just like before PHP supported namespaces.
The namespace is declared using the keyword namespace
. If a file contains a namespace, it must declare the namespace before all other code. The syntax format is as follows;
<?php // 定义代码在 'MyProject' 命名空间中 namespace MyProject; // ... 代码 ...
And, we can define different namespace codes in the same file. However, when combining code in a global non-namespace with code in a namespace, only the syntax within curly braces can be used. Global code must be enclosed in curly braces with unnamed namespace statements.
At the same time, the only valid code before declaring the namespace is the declare statement that defines the source file encoding. All non-PHP code (including whitespace) must not appear before a namespace declaration.
That’s it for naming the namespace. If you want to know more, you can click here. → →php video tutorial
The above is the detailed content of How to define space in php namespace?. For more information, please follow other related articles on the PHP Chinese website!