官方定义:
__autoload 尝试加载未定义的类 (函数已自 PHP 7.2.0 起被废弃,并自 PHP 8.0.0 起被移除)
spl_autoload_register 注册给定的函数作为 __autoload 的实现 (新版本的还是要用这个函数)
__aotoload 这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面的一
个简单例子:
index.php:
<?php
Class Index{
public function CheckIndex()
{
echo 'hello world';die;
}
}
main.php
<?php
function __autoload($ClassName) {
$file = $ClassName.'.php';
if(is_file($file)) {
include_once($file);
} else { // 找不到就抛出错误异常
}
}
$Obj = new Index();
$Obj->CheckIndex();
运行 main.php 就会输出hello world 在main.php中由于没有包含index.php 所以出发了自动加载的函数__autoload() 参数$ClassName的值就是类名index,这时判断类名存在不存在 如果存在就包含进来 这种方式一般都用在面向对象中 可以避免书写过多的引用文件。
来看下 spl_autoload_register 的简单实例:
<?
function autoload( $ClassName) {
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register( 'autoload' );
$obj = new Index();
$obj->CheckIndex();
将spl_autoload_register换成autoload函数,但是autoload 不会像__autoload 一样自动触发,这时候spl_aotoload_register就起了作用 它告诉php碰到了没有定义的类 然后就执行了autoload方法
详情参见:PHP官方手册 spl_aotoload_register(); __autoload();