spl_autoload_register函数用法

  1. 概念

注册给定的函数作为 __autoload 的实现;

也就是说当我们在A.php中实例化B.php文件中的类的时候,是需要先include/required一下B.php文件,然后才能找到B.php中相应的类。但是这样往往很麻烦。所以我们可以使用spl_autoload_register函数。

spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) : bool
  • autoload_function 当new一个类的时候,在本文件中没有找到相应的类。这时候自动调用autoload_function
    函数。
  • throw autoload_function 无法成功注册时, spl_autoload_register()是否抛出异常。
  • prepend 如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。
<?php

spl_autoload_register('registerFun', true, true);

function registerFun($classname) {
    echo '自动执行'.$classname.'--';
    include('2.php');
}
$newClass = new myClass();
//结果  自动执行myClass--
  1. 数组参数

If your autoload function is a class method, you can call spl_autoload_register with an array specifying the class and the method to run.
如果你自动加载的是一个类里面的函数的话,这时候你可以在spl_autoload_register函数的参数里指定一个数组去运行它。

这里的例子代码使用的是laravel框架的代码,spl_autoload_register函数的数组参数代表的是调用ComposerAutoloaderInit549127980f1a1f0673ee458d4c50ef43类里的loadClassLoader方法.

spl_autoload_register(array('ComposerAutoloaderInit549127980f1a1f0673ee458d4c50ef43', 'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
        spl_autoload_unregister(array('
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值