The advantage of adding namespace to PHP is to facilitate automatic loading

不言
Release: 2023-03-25 11:08:02
Original
1515 people have browsed it

This article mainly introduces the benefits of adding namespaces to PHP to facilitate automatic loading. It has a certain reference value. Now I share it with you. Friends in need can refer to it

A PHP project , usually there is only one entry file index.php. We usually write an automatic loading function in this entry file to require class files that will be instantiated in the future. For example:

spl_autoload_register(function ($className) {    require 'class/' . $className . '.php';});通过以上的代码,我们发现:在自动加载时,我们需要指定存放类的文件夹,以便找到相应的类。那么问题产生了。在引入命名空间之前:
Copy after login

Our project directory

index.php

##Controller.php

In index.php we need to instantiate a Controller class in the controller directory and call the model() method of this object, and this method needs to instantiate a Controller class in the model directory. Model class. Let’s run index.php:

Warning: require(controller/Model.php): failed to open stream: No such file or directory

Prompt that there is no such file or directory. The reason is very simple: when PHP uses new Model(), it automatically goes to the controller directory to require, so it cannot be found.

So, how should our automatic loading function be written to solve the problem? Obviously, changing 'controller/' to 'model/' or not writing the directory will not load properly. Therefore, the benefits of using namespaces emerge.

引入命名空间之后:
Copy after login

index.php

 

Controller.php

 

 

Model.php

我们按照文件目录的结构来为每个类写入命名空间,当在一个类中需要实例化另外一个类时,IDE会帮我们写入use namespace ;  。这样,我们在写自动加载的时候,就不用考虑将要加载的类在哪一个文件目录下了,只需要这样写:

spl_autoload_register(function ($class) {    require $class . '.php';});因为我们在index.php中use了所用到的类的命名空间,自动加载函数会到相应的命名空间中去寻找类(上述代码中的$class就相当于是'controller\Controller'),而这些类中又需要实例化其他的类,因为这些类中也声明了use 其他类的命名空间 ;,所以自动加载函数又会去相应的命名空间中去require其他类。这样,我们就不会为加载类而发愁了,极大地解放了我们的编程负担。
Copy after login

相关推荐:

无需重新编译php加入ftp扩展的方法

PHP加入数据程序的具体实现方法

The above is the detailed content of The advantage of adding namespace to PHP is to facilitate automatic loading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template