This article will give you a brief introduction to the __autoload() method of automatically loading classes in PHP. I hope this method will be helpful to all students.
Function: When you need to instantiate a class in the program, and this class is not in this file, you need to use the include function to include the external file. However, when there are many external classes to be used, you will find that using included functions will be very cumbersome. In this case, you can use the __autoload() global function to automatically load classes.
When you want to use the first three classes in index.php, you need to write three methods such as include("name.class.php"), which will be very inefficient, but if you use __autoload() Functions don’t have to be so troublesome. You only need to write a function method like this:
In PHP 5, this is no longer necessary. You can define an __autoload() function that is automatically called when trying to use a class that has not yet been defined. By calling this function, the scripting engine has a last chance to load the required classes before PHP fails with an error.
The following example will illustrate how __autoload() is used.
First define a class ClassA, the file name is ClassA.class.php
The code is as follows | Copy code | ||||||||||||
public function funa(){ echo "classA loaded successfully! ";
}
|
The code is as follows | Copy code |
class ClassB extends ClassA {
";
|
Finally, define another autoload.php in the same directory as the above two files (you can choose this file name as you like)
The code is as follows | Copy code |
代码如下 | 复制代码 |
index.php function __autoload($className){ //ucfirst() 将字符串首字母变为大写 include("ucfirst($className)".class.".php"); } /************** |
The code is as follows | Copy code |
index.php function __autoload($className){ //ucfirst() changes the first letter of the string to uppercase include("ucfirst($className)".class.".php"); } /****************** |
*For example: Instantiate the User class in User.class.php in the index.php file. If it does not exist, automatically call the __autoload() function
The code is as follows
|
Copy code | ||||
*************/