php自动加载函数spl_autoload_register和__autoload

本文深入探讨PHP自动加载机制,对比__autoload与spl_autoload_register函数,解析其在大型项目中的应用与优势,以及如何实现类的自动加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php自动加载函数

思考:

  • 为什么需要自动加载?
  • 自动加载函数有哪些?
  • 对于自动加载函数的区别和选择理由

为什么需要自动加载

现在我么来建一个小项目

  1. 目录结构:
| AotuLoad
| - Controller
| - - TestController.php
| - Model
| - - TestModel.php
| - index.php
  1. TestController.php
namespace AotoLoad\Controller;

use AotoLoad\Model\TestModel;

class TestController {
    public function test(){
        $model = new TestModel();
        echo  $model->test();
    }
}
  1. TestModel.php
namespace AotoLoad\Model;

class TestModel{
    public function test(){
        return 'TestModel->test()';
    }
}
  1. index.php
require_once __DIR__.'\Controller\TestController.php';
require_once __DIR__.'\Model\TestModel.php';
$controller = new AotoLoad\Controller\TestController();

$controller->test();//这是能正常运行的

我们想要在index.php中使用TestController.php 就必须引入使用到的所有文件,否则就会报错。所以在大型项目中,不使用自动加载就会出现无数个require_once,所以这时候自动加载就出现了。

自动加载函数 __autoload($class)

/**
 * php程序在发现使用的类没有被包含的话 会执行这个方法
 * @param $class 包含namesoace+类名
 */
function __autoload ($class){
    
}

修改index.php:

//require_once __DIR__.'\Controller\TestController.php';
//require_once __DIR__.'\Model\TestModel.php';

function  __autoload($class){
    $classPath = dirname(__DIR__).'\\'.$class.'.php';
    if(file_exists($classPath)){
        require_once ($classPath);
    }else{
        echo $classPath."不存在";
    }
}
$controller = new AotoLoad\Controller\TestController();

$controller->test();

没有报错,输出:

TestModel->test()

自动加载函数 spl_autoload_register

(PHP >= 5.1.2)

/**
 * @param $autoload_function 回调函数
 * @param $throw 此参数指定当无法注册autoload_函数时,spl_autoload_register()是否应引发异常。默认为true
 * @param $prepend 如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。
 */
function spl_autoload_register ($autoload_function = null, $throw = true, $prepend = false) {}

修改index.php:

//require_once __DIR__.'\Controller\TestController.php';
//require_once __DIR__.'\Model\TestModel.php';

function  test_autoload($class){
    $classPath = dirname(__DIR__).'\\'.$class.'.php';
    if(file_exists($classPath)){
        require_once ($classPath);
    }else{
        echo $classPath."不存在";
    }
}
spl_autoload_register('test_autoload');
$controller = new AotoLoad\Controller\TestController();

$controller->test();

为什么__autoload()函数最后还是被废弃了呢?

  1. 因为随着php的发展,项目越来越大,当一个php项目大到一定程度时可能会遇到需要调用不同项目的文件,因为__autoload函数不能被多次调用,所以就不适用了,
  2. php5.3之前 __autoload函数的错误不能被catch函数捕获,会抛出致命错误,5.3之后才能够 thrown 自定义的异常(Exception),随后自定义异常类即可使用。 __autoload 函数可以递归的自动加载自定义异常类。

优胜劣汰,官方推出了新的加载函数 spl_autoload_register,无论在加载方面还是异常捕获方面都很友好,而且spl_autoload_register的使用扩展性还很好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值