提出
在命名空间提出之前,不同的组件很容易碰到命名的冲突,例如 Request 、Response 等常见的命名。PHP 在 5.3 后提出了命名空间用来解决组件之间的命名冲突问题,主要参考了文件系统的设计:
同一个目录下不允许有相同的文件名 - 同一个命名空间下不允许有相同的类;
不同的目录可以有同名文件 - 不同的命名空间可以有相同的类;
定义
使用 namespace 关键字来定义一个命名空间。其中,顶层命名空间通常为厂商名,不同开发者的厂商命名空间是唯一的。命名空间不需要与文件目录一一对应,但是最好遵守 PSR-4 规范。
<?php
namespace Symfony\Component\HttpFoundation;
class Request {
}命名空间必须在所有代码之前声明,唯一的例外就是 declare 关键字。
<?php declare(strict_types=1); namespace App;
命名空间内可包含任意 PHP 代码,但是仅对类 (包括抽象类和 Trait)、接口、函数和常量这四种类型生效。
<?php
namespace MyProject;
const CONNECT_OK = 1;
class FOO {}
interface Foo{}
function foo() {}使用
使用 use 关键字来引入命名空间
<?php
namespace App;
use Symfony\Component\HttpFoundation\Request;
use Foo\Bar;
class Test {
public function run()
{
$bar = new Bar();
}
}定义和使用推荐遵循 PSR-2 的规范
namespace 之后必须存在一个空行;
所有 use 声明必须位于 namespace 声明之后;
每条 use 声明必须只有一个 use 关键字。
use 语句块之后必须存在一个空行。
当 use 引入的类出现同名时,可使用 as 来定义别名
<?php
namespace App;
use Foo\Bar as BaseBar;
class Bar extends BaseBar {
}限定符
除了使用 use 外,还可以直接使用 \ 限定符来进行解析,规则很简单:如果含有 \ 前缀则代表从全局命名空间开始解析,否则则代表从当前命名空间开始解析。
<?php namespace App; \Foo\Bar\foo(); // 解析成 \Foo\Bar\foo(); Foo\Bar\foo(); // 解析成 App\Foo\Bar\foo();
此规则也适用于函数、常量等
$a = \strlen('hi'); // 调用全局函数 strlen $b = \INI_ALL; // 访问全局常量 INI_ALL $c = new \Exception('error'); // 实例化全局类 Exception
有两个需要特别注意的地方:
对于函数和常量而言,如果当前命名空间不存在,则会自动去全局命名空间去寻找,因此可省略 \ 前缀。对于类而言,如果当前命名空间解析不到,不会去全局空间寻找,因此,不可省略 \
$a = strlen('hi'); $b = INI_ALL; $c = new Exception('error'); // 错误 $c = new \Exception('error'); // 正确
当动态调用命名空间时,该命名空间始终会被当成是全局命名空间,因此可以省略前缀 \
$class1 = 'Foo\Bar'; $object1 = new $class1; // 始终被解析成 \Foo\Bar
在内部访问命名空间
PHP 支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__ 魔术常量和 namespace 关键字。
__NAMESPACE__ 常量的值是包含当前命名空间名称的字符串,如果是在全局命名空间,则返回空字符串。
<?php
namespace MyProject;
function get($classname)
{
$a = __NAMESPACE__ . '\\' . $classname;
return new $a;
}关键字 namespace 可用来显式访问当前命名空间或子命名空间中的元素。它等价于类中的 self 操作符
namespace App; use blah\blah as mine; blah\mine(); // App\blah\mine() namespace\blah\mine(); // App\blah\mine() namespace\func(); // App\func() namespace\sub\func(); // App\sub\func() namespace\cname::method(); // App\cname::method() $a = new namespace\sub\cname(); // App\sub\cname $b = namespace\CONSTANT; // App\CONSTANT
转义 \ 符号
此外,推荐对所有的 \ 进行转义,避免出现不可预期的后果
$class = "dangerous\name"; // \n 被解析成换行符 $obj = new $class; $class = 'dangerous\name'; // 正确,但是不推荐 $class = 'dangerous\\name'; // 推荐 $class = "dangerous\\name"; // 推荐
The above is the detailed content of PHP core features namespace. For more information, please follow other related articles on the PHP Chinese website!
PHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AMPHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
PHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AMPHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.
Choosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AMPHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
PHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AMPHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.
PHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AMPHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AMPHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AMIn PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.
PHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AMPHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment






