PHP自动加载-spl_autoload_register

spl_autoload_register 自动加载
spl : Standard PHP library (标准PHP库)

首先来了解 __autoload

print.class.php

1 php
2     class print {
3         function doPrint(){
4             echo 'hello world';
5         }
6     }
7 ?>

index.php

 1 php
 2     // 这段即是 autoload的自动加载
 3     function __autoload($class){
 4         $file = $class.'.class.php';
 5         if (is_file($file)){
 6             require_once($file);
 7         }
 8     }
 9     
10     $obj = new print();
11     $obj->doPrint(); // 打印 'hello world'
12 ?>

index.php 的代码里面如果没有 autoload那段,则会直接不能运行,因为new 的对象都找不到。

PHPstorm编辑器 会帮你找到,但是程序跑起来的时候是有问题的。

spl_autoload_register

 1 php
 2     function load($class){
 3         $file = $class.'.class.php';
 4         if (is_file($file)){
 5             require_once ($file);
 6         }
 7     }
 8     
 9     spl_autoload_register('load');
10     $obj = new print();
11     $obj->doPrint(); // 打印 'hello world'
12 ?>

 spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) : bool 

有三个参数

spl_autoload_register(autoload_function, [throw], [prepend])

  1. autoload_funtion : 欲自动装载的函数,如果没有提供的话,则自动注册autoload的默认实现spl_autoload()
  2. throw : 设置 autoload_function 无法成功注册的时候是否 抛出异常  (true)
  3. prepend : 添加函数到队列之首,而不是队列尾部 (true)
1 // 自 PHP 5.3.0 起可以使用一个匿名函数
2 spl_autoload_register(function ($class) {
3     include 'classes/' . $class . '.class.php';
4 });

 

你可能感兴趣的:(PHP自动加载-spl_autoload_register)