Table of Contents
相关推荐:
Home Backend Development PHP Tutorial Usage of PHP command space namespace and use (example)

Usage of PHP command space namespace and use (example)

May 17, 2018 am 10:02 AM
namespace php Example

This article mainly introduces the practical summary of the usage of PHP command space namespace and use. Friends who need it can refer to it.

One of the clearest purposes of namespace is to solve the problem of duplicate names. Two names are not allowed in PHP. If two functions or classes have the same name, a fatal error will occur. In this case, it can be solved as long as you avoid naming duplication. The most common way is to agree on a prefix.

The purpose of using namespace:

When working on a team project, avoid conflicts with classes created by other team members; when individuals are responsible for the project, Avoid conflicts between newly created classes;

According to personal understanding, when using the required class, it needs to be introduced by require or include first, so the premise for a class redefinition error to occur is: two identically named classes Classes have been introduced. Currently, some PHP frameworks will automatically load (i.e. include) all newly created model classes, so in order to avoid name conflicts between your new model classes and the native core classes of the project framework, namespace is used. (After thinking about it, conflicts with new classes created by team members should be avoided through communication. Even after the incident, the class name should be readjusted and maintained immediately to avoid increased maintenance complexity caused by confusion in the understanding of the class later.)

Combined the usage methods to further understand its purpose.

How to use namespace:

For testing, I will create 3 files: 1.php and name.php (this file Used to perform tests), which will not be explained later. Please pay attention to the code changes yourself.

1. The definition of the name after namespace is not case-sensitive

namespace one;
namespace One;
namespace ONE;

Any of the above writing methods are acceptable, just choose one as your own standard. (I will use the first method for testing in the following code)

2. If there is no namespace defined, it is understood that the top-level namespace is used. When creating a new class, you can add a backslash\ before the class or not.

//1.php 
class Person{
 function __construct(){
  echo 'I am one!';
 }
}
//name.php
require_once './1.php';
new Person(); //输出 I am one!;
new \Person(); //输出 I am one!;
Copy after login

3. When adding a namespace to a new class, backslash characters must be used instead of forward slashes. Bar.

Memory method: Find the slashes in % in the order they are interpreted as forward slashes. (Sometimes when I say backslash, I don’t know which direction it is. I used to remember it in the ascending direction from left to right, but now I feel that this is too unreliable)

//name.php
require_once './1.php';
new /Person(); // 代码报错:Parse error: syntax error, unexpected '/'
Copy after login

4. The class is in the specified namespace. When new class, be sure to bring the specified namespace.

Without the specified namespace, according to point 2, PHP will find this class from the top-level namespace. Remember: This cannot be understood as the top-level namespace includes all other namespaces. Instead, the top-level namespace should be completely separated from other namespaces.

//1.php 
namespace one;
class Person{
 function __construct(){
  echo 'I am one!';
 }
}
//name.php
require_once './1.php';
new \one\Person(); //输出 I am one!;
new \Person(); //代码报错:Fatal error: Class 'Person' not found
Copy after login

You can take this popular example to understand: bring the specified namespace to represent someone’s apple (in his hand), and the top-level namespace represents the apple. Apples in the box (in the box). Now if you want to find someone's apple, you need to bring someone's namespace. Otherwise, you will look for someone's apple from the box, and of course you can't find it.

5. The code after the namespace declaration belongs to this namespace, even if there is include or require, it will not be affected (the focus is on the understanding of the second half of the sentence, see the code for details).

//1.php 
namespace one;
class Person{
 function __construct(){
  echo 'I am one!';
 }
}
//name.php
namespace test;
require './1.php'; 
new \one\Person(); //输出 I am one!;
new Person(); //这里结果会是什么呢,猜猜看
Copy after login

The last line results in an error:

Fatal error: Class 'test\Person' not found
Copy after login

First of all, here is the Compare the second point:

The second point, I said, when there is no namespace, when there is a new class, the meaning is the same whether there is a backslash or not.

Here, with the namespace, the meaning of having and not having backslashes is different.

Replace the last line with

new \Person();
Copy after login

and the result is an error:

Fatal error: Class 'Person' not found
Copy after login

Then, let’s talk about the current point.

We can find that the namespace corresponding to the last line of code is test and is not affected by the namespace in the require file.

To further strengthen the verification, I modified the name.php file as follows:

//name.php
namespace test;
require './1.php'; 
class Person{
 function __construct(){
  echo 'I am test!';
 }
}
new \one\Person(); //输出 I am one!;
new Person(); //这里结果会是什么,自己猜猜看
Copy after login

Finally, this example refreshed my understanding of require. .

According to my previous understanding of require: before the PHP program is executed, it will first read in the file specified by require, making it a part of the PHP program web page. So I often simply understand it as replacement, which is just putting the extracted code back into its original place. Then I tried putting the contents of the 1.php file into name.php:

//name.php
namespace test;
namespace one;
class Person{
 function __construct(){
  echo 'I am one!';
 }
}
class Person{
 function __construct(){
  echo 'I am test!';
 }
}
Copy after login

Without the new class, the file will report an error:

Fatal error: Cannot redeclare class one\Person

It seems that simply understanding require as replacement does not work here.

6. The namespace does not contain the class name. Even if there is a part with the same name as the class name, it does not represent the class. new class, you still have to bring this part.

//name.php
namespace test\person;
class Person{
 function __construct(){
  echo 'I am test!';
 }
}new \test\person\Person();  //命名空间里person无法代表类名
Copy after login

But this is purely superfluous, just go ahead and don’t include the class name in the namespace.

7. Multiple namespaces can exist in a php file, and there cannot be any code before the first namespace.

只说第一个命名空间前不能有任何代码,之后的命名空间之前可以有代码。这个自行测试即可。

//name.php
namespace test;
echo 'zhai14';
namespace zhai;
require './1.php';
Copy after login

php命名空间namespace告一段落了,接下来说说use的用途。

使用use的目的:

在命名空间字符串过长时,使用use可以相应的缩短命名空间。

use的使用方法:

1.new类时,最前面无需用反斜杠。此外,use后没有as时,缩短的命名空间默认为最后一个反斜杠后的内容。

//name.php
namespace animal\dog;
class Life{
 function __construct(){
  echo 'dog life!';
 }
}
namespace animal\cat;
class Life{
 function __construct(){
  echo 'cat life!';
 }
}
new Life(); //按照代码执行顺序,这里默认animal\cat这个命名空间
new \animal\dog\Life(); //A
use animal\dog; //a
new dog\Life(); //B
use animal\dog as d; //b
new d\Life();
Copy after login

通过A、B行代码比较,需要注意:

使用use后,new类时,最前面没有反斜杠。

没使用use时,命名空间最前面有反斜杠

通过a、b行代码比较,可以理解:

use后没有as时,缩短的命名空间默认为最后一个反斜杠后的内容。如上的:

use animal\dog;

相当于

use animal\dog as dog;

2.namespace后面不建议加类名,但use后可以。

//name.php
namespace animal\dog;
class Life{
 function __construct(){
  echo 'dog life!';
 }
}
namespace animal\cat;
class Life{
 function __construct(){
  echo 'cat life!';
 }
}
use animal\dog\Life as dog; 
new dog();
Copy after login

如上所示,use后加上类名后,就相当于把类改了个名称:由Life改为dog了。

上面不用as dog就会报错:

Fatal error: Cannot use animal\dog\Life as Life because the name is already in use
因为cat下也有个一样名称的Life类。

可以理解为,使用use后,这个昵称对应的类只能归当前命名空间占有,其它命名空间下不允许存在该类。

//name.php
namespace animal\dog;
class Life{
 function __construct(){
  echo 'dog life!';
 }
}
class Dog{
 function __construct(){
  echo 'dog in dog!';
 }
}
namespace animal\cat;
// class Dog{
// function __construct(){
//  echo 'dog in cat!';
//  }
// }
class Life{
 function __construct(){
  echo 'cat life!';
 }
}
use animal\dog; 
new dog\Dog();
Copy after login

如上,使用了

use animal\dog;
cat

通过上面代码,我想使用use的目的效果(缩短命名空间名称)就很明显了。

简单总结一下:

namespace就是划分领域的作用,代表这些东西是属于某个命名空间下的。

use就是起小名的作用,不论写起来还是说起来都可以省不少事儿。

相关推荐:

PHP命令空间的用法大全

php user_error()函数的简介

有关php user_error()函数的文章推荐10篇

The above is the detailed content of Usage of PHP command space namespace and use (example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles