


A brief analysis of automatic loading and namespace of PHP classes
浅析PHP类的自动加载和命名空间
php是使用require(require_once)和include(include_once)关键字加载类文件。但是在实际的开发工程中我们基本上不会去使用这些关键字去加载类。 因为这样做会使得代码的维护相当的困难。实际的开发中我们会在文件的开始位置用use关键字使用类,然后直接new这个类就可以了. 至于类是怎么加载的,一般都是框架或者composer去实现的。
<?php use Illuminate\Container\Container; $container = new Container();
自动加载
我们可以通过一段伪代码来模拟一下在类的实例化工程中类是如何工作的
function instance($class) { // 如果类已加载则返回其实例 if (class_exists($class, false)) { return new $class(); } // 查看 autoload 函数是否被用户定义 if (function_exists('__autoload')) { __autoload($class); // 最后一次加载类的机会 } // 再次检查类是否存在 if (class_exists($class, false)) { return new $class(); } else { // 系统:我实在没辙了 throw new Exception('Class Not Found'); } }
php在语言层面提供了**__autoload** 魔术方法给用户来实现自己的自动加载逻辑。当用户去new一个类的时候,如果该类没有被加载,php会在抛出错误前调用**__autoload方法去加载类。下面的例子中的__autoload**方法只是简单的输出要加载类的名称, 并没有去实际的加载对应的类, 所以会抛出错误。
<?php use Illuminate\Container\Container; $container = new Container(); function __autoload($class) { /* 具体处理逻辑 */ echo $class;// 简单的输出要加载类的名称 } /** *
运行结果
Illuminate\Container\Container Fatal error: Uncaught Error: Class 'Illuminate\Container\Container' not found in D:\project\php\laravel_for_ci_cd\test\ClassLoader.php:5 Stack trace: #0 {main} thrown in D:\project\php\laravel_for_ci_cd\test\ClassLoader.php on line 5 */
明白了 **__autoload** 函数的工作原理之后,我们来用它去实现一个最简单自动加载。我们会有index.php和Person.php两个文件在同一个目录下。
//index.php <?php function __autoload($class) { // 根据类名确定文件名 $file = './'.$class . '.php'; if (file_exists($file)) { include $file; // 引入PHP文件 } } new Person(); /*---------------------分割线-------------------------------------*/ //Person.php class Person { // 对象实例化时输出当前类名 function __construct() { echo '<h1>' . __CLASS__ . '</h1>'; } } /**运行结果 * 输出 <h1>Person</h1> */
命名空间
命名空间并不是什么新鲜的事务,很多语言都早就支持了这个特性(只是叫法不相同),它主要解决的一个问题就是命名冲突! 就好像日常生活中很多人都会重名,我们必须要通过一些标识来区分他们的不同。比如说现在我们要用php介绍一个叫张三的人 ,他在财务部门工作。我们可以这样描述。
namespace 财务部门; class 张三 { function __construct() { echo '财务部门的张三'; } }
这就是张三的基本资料 , namespace是他的部门标识,class是他的名称. 这样大家就可以知道他是财务部门的张三而不是工程部门的张三。
非限定名称,限定名称和完全限定名称
1.非限定名称,或不包含前缀的类名称,例如 $comment = new Comment(); 如果当前命名空间是Blog\Article,Comment将被解析为、\Blog\Article\Comment。如果使用Comment的代码不包含在任何命名空间中的代码(全局空间中),则Comment会被解析为\Comment。
注意: 如果文件的开头有使用use关键字 use one\two\Comment; 则Comment会被解析为 **one\two\Comment**。
2.限定名称,或包含前缀的名称,例如 $comment = new Article\Comment(); 如果当前的命名空间是Blog,则Comment会被解析为\Blog\Article\Comment。如果使用Comment的代码不包含在任何命名空间中的代码(全局空间中),则Comment会被解析为\Article\Comment。
3.完全限定名称,或包含了全局前缀操作符的名称,例如 $comment = new \Article\Comment(); 在这种情况下,Comment总是被解析为\Article\Comment。
spl_autoload
接下来让我们要在含有命名空间的情况下去实现类的自动加载。我们使用 spl_autoload_register() 函数来实现,这需要你的 PHP 版本号大于 5.12。spl_autoload_register函数的功能就是把传入的函数(参数可以为回调函数或函数名称形式)注册到 SPL __autoload 函数队列中,并移除系统默认的 **__autoload()** 函数。一旦调用 spl_autoload_register() 函数,当调用未定义类时,系统就会按顺序调用注册到 spl_autoload_register() 函数的所有函数,而**不是自动调用 __autoload()** 函数。
现在, 我们来创建一个 Linux 类,它使用 os 作为它的命名空间(建议文件名与类名保持一致):
<?php namespace os; // 命名空间 class Linux // 类名 { function __construct() { echo '<h1>' . __CLASS__ . '</h1>'; } }
接着,在同一个目录下新建一个 index.php文件,使用 spl_autoload_register 以函数回调的方式实现自动加载:
<?php spl_autoload_register(function ($class) { // class = os\Linux /* 限定类名路径映射 */ $class_map = array( // 限定类名 => 文件路径 'os\\Linux' => './Linux.php', ); /* 根据类名确定文件路径 */ $file = $class_map[$class]; /* 引入相关文件 */ if (file_exists($file)) { include $file; } }); new \os\Linux();
这里我们使用了一个数组去保存类名与文件路径的关系,这样当类名传入时,自动加载器就知道该引入哪个文件去加载这个类了。但是一旦文件多起来的话,映射数组会变得很长,这样的话维护起来会相当麻烦。如果命名能遵守统一的约定,就可以让自动加载器自动解析判断类文件所在的路径。接下来要介绍的PSR-4 就是一种被广泛采用的约定方式
PSR-4规范
PSR-4 是关于由文件路径自动载入对应类的相关规范,规范规定了一个完全限定类名需要具有以下结构:
<顶级命名空间>(<子命名空间>)*<类名>
PSR-4 规范中必须要有一个顶级命名空间,它的意义在于表示某一个特殊的目录(文件基目录)。子命名空间代表的是类文件相对于文件基目录的这一段路径(相对路径),类名则与文件名保持一致(注意大小写的区别)。
举个例子:在全限定类名 \app\view\news\Index 中,如果 app 代表 C:\Baidu,那么这个类的路径则是 C:\Baidu\view\news\Index.php.我们就以解析 \app\view\news\Index 为例,编写一个简单的 Demo:
<?php $class = 'app\view\news\Index'; /* 顶级命名空间路径映射 */ $vendor_map = array( 'app' => 'C:\Baidu', ); /* 解析类名为文件路径 */ $vendor = substr($class, 0, strpos($class, '\\')); // 取出顶级命名空间[app] $vendor_dir = $vendor_map[$vendor]; // 文件基目录[C:\Baidu] $rel_path = dirname(substr($class, strlen($vendor))); // 相对路径[/view/news] $file_name = basename($class) . '.php'; // 文件名[Index.php] /* 输出文件所在路径 */ echo $vendor_dir . $rel_path . DIRECTORY_SEPARATOR . $file_name;
更多PHP相关知识,请访问PHP中文网!
The above is the detailed content of A brief analysis of automatic loading and namespace of PHP classes. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Solve PHP error: The specified namespace class was not found. When developing using PHP, we often encounter various error messages. One of the common errors is "The specified namespace class was not found". This error is usually caused by the imported class file not being properly namespace referenced. This article explains how to solve this problem and provides some code examples. First, let’s take a look at an example of a common error message: Fatalerror:UncaughtError:C

Redis is an open source, high-performance key-value storage database. When using Redis for data storage, we need to consider the design of the key namespace and expiration mechanism to maintain Redis performance and data integrity. This article will introduce the design ideas and implementation methods of Redis' namespace and expiration mechanism. 1. Redis namespace design ideas In Redis, keys can be set arbitrarily. In order to facilitate the management and distinction of different data types, Redis introduces the concept of namespace. Life

The F3 framework is a simple, easy-to-use, flexible and scalable PHPWeb framework. Its namespace (Namespace) mechanism provides us with a more standardized, more readable, and clearer code structure. In this article, we will explore how to use namespaces in the F3 framework. 1. What is a namespace? Namespaces are often used to solve the problem of naming conflicts in PHP. It can encapsulate one or more classes, functions or constants in a namespace, which is equivalent to adding a prefix to them. example

C++ is a widely used high-level programming language. It has high flexibility and scalability, but it also requires developers to strictly master its grammatical rules to avoid errors. One of the common errors is "use of undefined namespace". This article explains what this error means, why it occurs, and how to fix it. 1. What is the use of undefined namespace? In C++, namespaces are a way of organizing reusable code in order to keep it modular and readable. You can use namespaces to make functions with the same name

As the PHP language becomes more and more popular, developers need to use more and more classes and functions. When a project grows in size, manually introducing all dependencies becomes impractical. At this time, an automatic loading mechanism is needed to simplify the code development and maintenance process. The auto-loading mechanism is a feature of the PHP language that can automatically load required classes and interfaces at runtime and reduce manual class file introduction. In this way, programmers can focus on developing code and reduce errors and time waste caused by tedious manual class introduction. In PHP, generally

Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Introduction: PHP8 is an important version of the PHP programming language, which introduces many exciting new features and improvements. One of the most important new features is namespaces. Namespaces are a way to organize your code into a better structure that avoids conflicts between classes, functions, and constants with the same name. In this article, we’ll look at how to leverage namespaces and codes to better structure your PHP8 code

It is crucial to manage custom functions using namespaces, which allow developers to create their own naming ranges and prevent name conflicts. The steps include: creating a namespace, using the use statement to import the namespace, and calling the namespace function. In a practical case, the MyMath extension demonstrates how to use namespaces to organize mathematical functions to improve readability and maintainability.

How to use PHP7's namespace and automatic loading mechanism to organize the structure of the code? Abstract: With the launch of PHP7, namespace and automatic loading mechanism have become important features that cannot be ignored in PHP development. This article will introduce how to use PHP7's namespace and automatic loading mechanism to organize the structure of the code, and illustrate it through specific code examples. 1. What is a namespace? Namespace is a mechanism introduced in PHP7 to resolve naming conflicts that may occur between different class libraries or code files. via namespace
