search
HomeBackend DevelopmentPHP TutorialPHP 命名空间 namespace / 类别名 use / 框架自动载入 机理的

从 php 5.3 起 PHP 多了 命名空间/延迟静态绑定/lambda匿名函数 等主要特性

命名空间的引用进一步提升了php的代码结构的灵活性和可控性,方便将项目的各工具类进行归类管理

各 php 框架则是利用命名空间做文件路径映射自动加载的功能 

下面我们拿 Yii2 做一次剖析

先看一下 Yii2的控制器书写规则

controllers\IndexController.php

<?php /** * 自动载入机制 *///==========================================================================================//声明自己的命名空间 此命名空间下的类皆归属于此命名空间管理//==========================================================================================namespace app\controllers;//==========================================================================================//use 声明其实只是为 yii\web\Controller 定义一个别名:Controller 方便我们再上下文中使用//而并非像 C/C++的include JAVA的import将导入的文件加载进来(当然php为解释语言 不存在预编译这一步)//==========================================================================================use yii\web\Controller;//==========================================================================================//IndexController的完整类名其实为 app\controller\IndexController//Controller 为 yii\web\Controller php 解释到此点才会去加载此类//==========================================================================================class IndexController extends Controller {    public function actionIndex() {        //不使用 use 提前声明 手写完整的类名        $model = new \app\models\EntryForm();//注意当前上下文中存在命名空间 所以要从根命名空间 '\' 开始    }}?>

1、某命名空间下的类 的完整名称为 namespace\className,当在某命名空间上下文中访问其它命名空间下的类时,我们可以使用 use 做别名化,或者使用此类的完整名称,但要以 '\' 根命名空间开头,否则解释器会认为你是在当前命名空间上下文中调用,即 foo\bar 方式会以 currentNamespace\foo\bar的方式去加载

命名空间与linux文件系统很相似,'\' 代表根,不以根开始的皆认为以当前命名空间为基点

2、use 只是给你使用的类定义短别名,use foo\bar 后则new bar() 即new  \foo\bar(),还有个小技巧,当我们同时引用不同命名空间下的类名相同的类时可以使用 as 为其定义一个新别名

use foo\bar\sameName as classA;use bar\foo\sameName as classB;new classA(); // new \foo\bar\sameName;new classB(); // new \bar\foo\sameName;

3、当我们通过 入口文件 加载参数配置 实例化一个应用主体 加载路由组件解析请求 分派控制器调用方法时,期间会调用其他的类,比如 

use yii\web\Controller;

系统便会去通过自动载入函数做最一次载入尝试,若仍加载不到此类则报错

下面我们看下 Yii2 从入口文件开始一个应用实体后注册自动载入函数的流程

index.php

入口文件载入配置和系统框架时会使用require调用,因为现在还没有注册自动加载函数

载入 Yii bootstrap 文件时便通过 spl_autoload_register 注册了自动载入函数 

Yii.php

Yii2的自动载入函数

继承至 BaseYii 它要做的就是根据你命名空间类型的类名去映射为此类所在的文件路径

比如 yii\web\Controller类会根据 yii 而映射到  YII2_PATH . '/web/Controller.php' 文件中,而这个文件则是命名空间为 yii\web 的 Controller 类,将此文件载入即可访问 yii\web\Controller 类

而我们自己编写的控制器或者模型则访问时为 'app\controllers\IndexController' 'app\models\EntryForm'

则 autoload 函数会根据 app 为 映射关键字将其定位到 controllers 或 models 文件夹下从而读取对应的文件即可载入相应的类,这也是为什么 类名 与 文件名 相互对应的原因所在,若不存在对应,则你只能通过固定的 require 某个文件去加载你写在其中的类了 

Statement
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
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

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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

DVWA

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools