Home > Article > Backend Development > PHP object-oriented - code example to implement automatic loading class __autoload()
When designing object-oriented program development, a separate PHP source file is usually created for the definition of each class. When you try to use an undefined class, PHP will report a fatal error. You can use include or require to include the source file where a class is located, after all you know which class you want to use. If a page needs to use multiple classes, you have to write a long list of include files at the beginning of the script page to include all the classes needed for this page. This processing is not only cumbersome, but also error-prone.
PHP provides the automatic loading function of classes, which can save programming time. When you try to use a class that PHP is not organized into, it will look for a global function of autoload() (not a function declared in the class). If this function exists, PHP will call it with one parameter, which is the name of the class.
The following example illustrates how autoload() is used. It assumes that each file in the current directory corresponds to a class. When the script attempts to create an instance of the User class, PHP will automatically execute the autoload() function. The script assumes that the User class is defined in user.class.php. Regardless of whether it is called in uppercase or lowercase, PHP will return the lowercase name. Therefore, when working on a project, when organizing and defining the file names of classes, you need to follow certain rules. The class name must be the center. You can also add a unified prefix or suffix to the file name, such as classname.class.php, xxx_classname.php, classname_xxx.php or classname.php, etc. It is recommended to use the "classname.class.php" format for naming class files.
<?php/* 声明一个自动加载类的魔术方法autoload() */function autoload($className){ //在方法中使用include包含类所在的文件 include(strtolower($className) . ".class.php"); }$obj = new User(); //User类不存在,则自动调用autoload()函数,将类名“User”作为参数传入$obj2 = new shop(); ?>
The above is the detailed content of PHP object-oriented - code example to implement automatic loading class __autoload(). For more information, please follow other related articles on the PHP Chinese website!