Home > Article > Backend Development > Detailed explanation of how to use spl_autoload_register to implement automatic loading of instances
spl_autoload_register()Function should be the mainstream FrameworkThe most used and one of the very core functions, which can realize automatic registration of functions and classes, and achieve functions similar to autoload(). It simplifies the calling and loading of classes and improves the efficiency of work
Here we will talk about some features of this function through an experiment.
Function prototype
bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
Version compatible
PHP 5 > ;= 5.1.2
Experimental process
The first step is to use the spl_autoload_register() function to register the load() method
The code is as follows:
<?php function load(){ require_once'lib.php'; } spl_autoload_register('load'); ?>
The lib.php file code is as follows
The code is as follows:
<?php class className{ function method(){ echo 'a method in class'; } } function onlyMethod(){ echo 'method only'; } ?>
Explanation: The lib.php file is a className class and an onlyMethod function
Second Step, call Automatically load the class
The code is as follows:
$class = new className(); $class->method(); onlyMethod();
Output:
a method in class method only
Description: Instantiate the className class, And call the class method() function and the onlyMethod() method at the same time. The output is normal and no errors occur.
The third step is to call the function directly
onlyMethod();
Instructions: None Instantiate the class and directly call the onlyMethod() function in the lib.php file
Output:
Fatal error: Call to undefined function onlyMethod() in '...(omitted path)'
The fourth step is to instantiate the className class and then directly call
$class = new className(); onlyMethod();
Output: method only
From the above four-step experiment, it is found that if the loaded file contains a function, it must be used The classes inside need to be instantiated, otherwise an abnormal Call to undefined function error will occur. Please pay attention to it when using it.
The above is the detailed content of Detailed explanation of how to use spl_autoload_register to implement automatic loading of instances. For more information, please follow other related articles on the PHP Chinese website!