


A brief introduction to the usage of autoloading class __autoload()
在面向对象编程中,都是以对象为单位的操作,如果我有两个不同的类,类A和类B,在同一个文件里,实例化对象,就能在这个文件同时调用类A和类B的函数
<?php #a.php class A{ public function funA() { echo 'The class:'.class.'<br/>'; } } class B{ public function funB() { echo 'The class:'.class.'<br/>'; } } $a = new A(); $b = new B(); $a->funA(); //The class:A $b->funB(); //The class:B
两个类都在同一个文件,所有能运行成功,但现在大部分应用都分MVC,不同类专门处理特定的事物,比如C(Controller),只执行与事物有关的逻辑操作,这些文件很明显分属于不同目录下:
|—root
|—controller
|—controllerA.php
|—model
|—modelA.php
|—view
|—viewA.php
这时我要在modelA.php里怎么引用controllerA.php的函数呢?这就用到autoload()了。
<?php #保存在MyClass.php class MyClass { public function getNamespace() { return get_class($this); } }
现在我们在同级目录下引用这个类
<?php function autoload($name) { $file = realpath(DIR).'/'.$name.'.php'; if(file_exists($file)) { require_once($file); if(class_exists($name,false)) { return true; } return false; } return false; } $obj = new MyClass(); echo $obj->getNamespace(); //输出 MyClass;
当你引用不存在的类时,autoload就会被调用,并且你的类名会被作为参数传送过去(当你同时使用命名空间,包含命名空间部分会一起作为参数传送)。
下面我们把命名空间和自动加载类合并使用
命名空间,PHP从5.3开始支持命名空间(namespace),这个在C语言里非常常见,刚开始我不理解,直到我完整接触一个项目,需要加载在不同目录下Class时,恍然大悟。OK,下面讲一讲自己的理解吧。
用不同的命名空间区别相同的函数名,同时命名空间也可以作为引入类文件的路径。
(在WEB项目中,当在client输入一个url时,一般会有一个入口文件,在这个文件里解析你要调用的controller,以及传递的参数,然后动态的加载相应类文件,这其实就牵扯到一点路由规则,当然还有另外一种,在项目初始化之初就把所有类文件全部加载在内存中,这样,每次请求响应都不用再加载,常驻内存后响应要快点。)
<?php #首先建立一个MyClass目录,在该目录下新MyClass.php文件,代码如下。 namespace MyClass; class MyClass { public function getNamespace() { return get_class($this); } }
<?php #在跟MyClass目录同级的目录下,新建一个文件,内容如下 function autoload($name) { $class_path = str_replace('\\',DIRECTORY_SEPARATOR,$name); //把表示命名空间的分割符号,转换成表示目录结构的斜线 $file = realpath(DIR).'/'.$class_path.'.php'; if(file_exists($file)) { require_once($file); //引入文件 if(class_exists($name,false)) //带有命名空间的类名 { return true; } return false; } return false; } echo MyClass\MyClass::getNamespace(); //输出: MyClass\MyClass;
这样非常容易避免了,当一个项目非常大时,不停的require文件。
让我们再思考,有没有更工程化的解决方案?当然有,我们可以建立自己的 Autoload 类,在这个类里面自动加载不同的类(可以包含命名空间),需要引用其他类的文件,只需要显示写入这个 Autoload 类即可。
The above is the detailed content of A brief introduction to the usage of autoloading class __autoload(). 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


![Error loading plugin in Illustrator [Fixed]](https://img.php.cn/upload/article/000/465/014/170831522770626.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

With the development of the Internet, more and more web pages need to support scrolling loading, and infinite scrolling loading is one of them. It allows the page to continuously load new content, allowing users to browse the web more smoothly. In this article, we will introduce how to implement infinite scroll loading using PHP. 1. What is infinite scroll loading? Infinite scroll loading is a method of loading web content based on scroll bars. Its principle is that when the user scrolls to the bottom of the page, background data is asynchronously retrieved through AJAX to continuously load new content. This kind of loading method

Preface: vim is a powerful text editing tool, which is very popular on Linux. Recently, I encountered a strange problem when using vim on another server: when I copied and pasted a locally written script into a blank file on the server, automatic indentation occurred. To use a simple example, the script I wrote locally is as follows: aaabbbcccddd. When I copy the above content and paste it into a blank file on the server, what I get is: aabbbcccddd. Obviously, this is what vim does automatically for us. Format indentation. However, this automatic is a bit unintelligent. Record the solution here. Solution: Set the .vimrc configuration file in our home directory, new

With the development of the Internet, pictures have become an indispensable part of web pages. But as the number of images increases, the loading speed of images has become a very important issue. In order to solve this problem, many websites use thumbnails to display images, but in order to generate thumbnails, we need to use professional image processing tools, which is a very troublesome thing for some non-professionals. Then, using JavaScript to achieve automatic thumbnail generation becomes a good choice. How to use JavaS

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

If you are using a Linux operating system and want the system to automatically mount the drive on boot, you can do this by adding the device's unique identifier (UID) and mount point path to the fstab configuration file. fstab is a file system table file located in the /etc directory. It contains information about the file systems that need to be mounted when the system starts. By editing the fstab file, you can ensure that the required drives are loaded correctly every time the system starts, thus ensuring stable system operation. Automatically mounting drivers can be conveniently used in a variety of situations. For example, I plan to back up my system to an external storage device. To achieve automation, ensure that the device remains connected to the system, even at startup. Likewise, many applications will directly

The solutions to the problem that CSS cannot be loaded include checking the file path, checking the file content, clearing the browser cache, checking the server settings, using developer tools and checking the network connection. Detailed introduction: 1. Check the file path. First, please make sure the path of the CSS file is correct. If the CSS file is located in a different part or subdirectory of the website, you need to provide the correct path. If the CSS file is located in the root directory, the path should be direct. ; 2. Check the file content. If the path is correct, the problem may lie in the CSS file itself. Open the CSS file to check, etc.
