Home >Backend Development >PHP Tutorial >PHP spl_autoload_register implements automatic loading research_PHP tutorial

PHP spl_autoload_register implements automatic loading research_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:22:36870browse

Here we talk about some characteristics 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, use the spl_autoload_register() function to register the load() method

Copy code The code is as follows:

function load(){
require_once 'lib.php';
}
spl_autoload_register('load');
?>


The lib.php file code is as follows
Copy the codeThe code is as follows:

class className{
function method(){
echo 'a method in class';
}
}

function onlyMethod (){
echo 'method only';
}
?>

Description: The lib.php file is a className class and an onlyMethod function

The second step is to call the automatically loaded class
Copy the code The code is as follows:

$class = new className();
$class->method();
onlyMethod();

Output:
a method in class
method only

Description: Example Transform 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 directly call the function

onlyMethod();

Note: There is no instantiated class, directly call the onlyMethod() function in the lib.php file
Output:
Fatal error: Call to undefined function onlyMethod() in '...(omit path) '

The fourth step, instantiate the className class, and then directly call

$class = new className();
onlyMethod();

Output: method only

From the above four-step experiment, we found that if the loaded file contains a function, the class inside must be instantiated, otherwise an abnormal Call to undefined function error will occur. Please pay attention to it during use.

Participation information: spl_autoload_register

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324679.htmlTechArticleHere we will talk about some characteristics of this function through an experiment. Function prototype bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn