当前位置:Gxlcms > PHP教程 > php函数spl_autoload_register的用法详解

php函数spl_autoload_register的用法详解

时间:2021-07-01 10:21:17 帮助过:31人阅读

  1. class A{
  2.   public function __construct(){
  3.     echo 'Got it.';
  4.   }
  5. }

然后,有一个index.php需要用到这个类A,常规写法:

  1. require('A.php');

  2. $a = new A();

问题所在: 假如index.php需要包含的不只是类A,而是需要很多类,则必须写很多行require语句。

在php5中,试图使用尚未定义的类时会自动调用__autoload函数,所以可以通过编写__autoload函数来让php自动加载类。

以上的例子,可以修改为:

  1. function __autoload($class) {

  2.   $file = $class . '.php';
  3.   if (is_file($file)) {
  4.     require_once($file);
  5.   }
  6. }

  7. $a = new A();

  8. __autoload只是去include_path寻找类文件并加载,我们可以根据自己的需要定义__autoload加载类的规则。

此外,假如不想自动加载的时候调用__autoload,而是调用自己的函数(或者类方法),可以使用spl_autoload_register来注册自己的autoload函数。

函数原型如下: bool spl_autoload_register ( [callback $autoload_function] )

继续修改以上的例子:

  1. function loader($class) {

  2.   $file = $class . '.php';
  3.   if (is_file($file)) {
  4.     require_once($file);
  5.   }
  6. }

  7. spl_autoload_register('loader');

  8. $a = new A();

php在寻找类时就没有调用__autoload而是调用自己定义的函数loader了。

以下写法也是可以的,例如:

  1. class Loader {

  2.   public static function loadClass($class) {
  3.     $file = $class . '.php';
  4.     if (is_file($file)) {
  5.       require_once($file);
  6.     }
  7.   }
  8. }

  9. spl_autoload_register(array('Loader', 'loadClass'));

  10. $a = new A();

人气教程排行