涉及到的两个函数

  • __autoload — 尝试加载未定义的类
  • spl_autoload_register — 注册给定的函数作为 __autoload 的实现
注: 如果在你的程序中已经实现了__autoload()函数,它必须显式注册到__autoload()队列中。因为 spl_autoload_register()函数会将Zend Engine中的__autoload()函数取代为spl_autoload()或spl_autoload_call()。

如何显示注册__autoload

spl_autoload_register('__autoload');

为什么用 spl_autoload_register

  1. 你的项目里引用了别人的一个项目,你的项目中有一个__autoload,别人的项目也有一个__autoload,这样两个__autoload就冲突了。解决的办法就是修改__autoload成为一个,这无疑是非常繁琐的。
  2. 如果需要多条 autoload 函数,spl_autoload_register() 满足了此类需求。 它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。相比之下, __autoload() 只可以定义一次。

ThinkPHP autoload

  1. 在TP入口文件,启动引导类,引导类中使用 spl_autoload_functions 注册了一个自动加载的静态方法。

Image

Image

  1. 例在D方法调用 class_exists('xxx\xx') 或直接 new xxx\xx 若不存在相应的类(xxx\xx),可触发 spl_autoload_functions 中注册的方法,即触发[类库自动加载]方法并传入类名('xxx\xx')。
文章目录