php多次自动加载冲突或导致后面加载无效

  • Jesse
  • 2017-08-18 16:27:00
  • 3432

使用spl_autoload_register自动加载类时,如果存在2个或多次spl_autoload_register时,

当第一次自动载入(require_once文件时),如果文件不存在就抛出异常或者终止时,后面的自动加载(spl_autoload_register)就会失效。

 

php手册上也有类似说明。

例如:

function genericAutoload($class) {
    if (!require_once($class . '.php')) {
        throw new Exception("Can't require_once!");
    } else {
        return true;
    }
}
function secondaryAutoload($class) {
    require_once('library/' . $class . '.php');
}

spl_autoload_register('genericAutoload');

spl_autoload_register('secondaryAutoload');

解决方法有两种,根据自己的业务需求来使用:

1.require_once文件时,如果文件不存在,不中断程序(如不抛出异常或不die),后面的自动加载依然有效;

 

2.使用spl_autoload_unregister注销第一个(前面的那个'自动加载'),这样会造成注销后的加载失效,可能会影响功能(推荐第一种)如:

spl_autoload_unregister('genericAutoload');



本文出自 亮有一技,转载时请注明出处及相应链接。