search
HomeBackend DevelopmentPHP TutorialPHP core features namespace

PHP core features namespace

Oct 31, 2019 pm 02:13 PM
php

提出

在命名空间提出之前,不同的组件很容易碰到命名的冲突,例如 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(&#39;hi&#39;); // 调用全局函数 strlen
$b = \INI_ALL; // 访问全局常量 INI_ALL
$c = new \Exception(&#39;error&#39;); // 实例化全局类 Exception

有两个需要特别注意的地方:

对于函数和常量而言,如果当前命名空间不存在,则会自动去全局命名空间去寻找,因此可省略 \ 前缀。对于类而言,如果当前命名空间解析不到,不会去全局空间寻找,因此,不可省略 \

$a = strlen(&#39;hi&#39;);
$b = INI_ALL;
$c = new Exception(&#39;error&#39;); // 错误
$c = new \Exception(&#39;error&#39;); // 正确

当动态调用命名空间时,该命名空间始终会被当成是全局命名空间,因此可以省略前缀 \

$class1 = &#39;Foo\Bar&#39;;
$object1 = new $class1;  // 始终被解析成 \Foo\Bar

在内部访问命名空间

PHP 支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__ 魔术常量和 namespace 关键字。

__NAMESPACE__ 常量的值是包含当前命名空间名称的字符串,如果是在全局命名空间,则返回空字符串。

<?php
namespace MyProject;
function get($classname)
{
    $a = __NAMESPACE__ . &#39;\\&#39; . $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 = &#39;dangerous\name&#39;; // 正确,但是不推荐
$class = &#39;dangerous\\name&#39;; // 推荐
$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!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.