PHP spl_autoload_register automatic loading research
- 2020-05-10 17:47:31
- OfStack
Here is an experiment to discuss some of the characteristics of this function.
The function prototype
bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
Version compatibility
PHP 5 > = 5.1.2
The experimental process
Step 1, register the load() method with the spl_autoload_register() function
The lib.php file code is as follows
Note: lib.php file for 1 className class and 1 onlyMethod function
Step 2, call the auto-load class
Output:
a method in class
method only
Note: instantiate the className class, and call the method() function of the class, and call the onlyMethod() method at the same time
Step 3, call the function directly
onlyMethod();
Note: without instantiating the class, directly call the onlyMethod() function in the lib.php file
Output:
Fatal error: Call to undefined function onlyMethod() in '... (omits the path)'
Step 4: instantiate the className class and call it directly
$class = new className();
onlyMethod();
Output: method only
From the above four-step experiment, it is found that if the loaded file contains functions, the class inside must be instantiated with 1, otherwise there will be an exception Call to undefined function error. Please pay attention to 1.
The function prototype
bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
Version compatibility
PHP 5 > = 5.1.2
The experimental process
Step 1, register the load() method with the spl_autoload_register() function
<?php
function load(){
require_once 'lib.php';
}
spl_autoload_register('load');
?>
The lib.php file code is as follows
<?php
class className{
function method(){
echo 'a method in class';
}
}
function onlyMethod(){
echo 'method only';
}
?>
Note: lib.php file for 1 className class and 1 onlyMethod function
Step 2, call the auto-load class
$class = new className();
$class->method();
onlyMethod();
Output:
a method in class
method only
Note: instantiate the className class, and call the method() function of the class, and call the onlyMethod() method at the same time
Step 3, call the function directly
onlyMethod();
Note: without instantiating the class, directly call the onlyMethod() function in the lib.php file
Output:
Fatal error: Call to undefined function onlyMethod() in '... (omits the path)'
Step 4: instantiate the className class and call it directly
$class = new className();
onlyMethod();
Output: method only
From the above four-step experiment, it is found that if the loaded file contains functions, the class inside must be instantiated with 1, otherwise there will be an exception Call to undefined function error. Please pay attention to 1.
Information of participation: spl_autoload_register