Home  >  Article  >  php教程  >  PHP spl_autoload_register实现自动加载研究

PHP spl_autoload_register实现自动加载研究

WBOY
WBOYOriginal
2016-06-13 12:03:48928browse

这里通过一个实验谈谈这个函数的部分特征。

函数原型
bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

版本兼容
PHP 5 >= 5.1.2

实验过程
第一步,使用spl_autoload_register()函数注册load()方法

复制代码 代码如下:


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



其中lib.php文件代码如下

复制代码 代码如下:


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

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


说明:lib.php文件为一个className类和一个onlyMethod函数

第二步,调用自动加载类

复制代码 代码如下:


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


输出:
a method in class
method only

说明:实例化className类,并调用类method()函数,同时调用onlyMethod()方法,输出正常,没有出现错误

第三步,直接调用函数

onlyMethod();

说明:没有实例化类,直接调用lib.php文件中的onlyMethod()函数
输出:
Fatal error: Call to undefined function onlyMethod() in '...(省略路径)'

第四步,实例化className类,再直接调用

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

输出:method only

从上面的四步实验发现,如果加载的文件包含函数,使用则一定需要实例化里面的类,否则就产生异常情况 Call to undefined function错误,具体在使用中要注意一下。

参与资料:spl_autoload_register

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