第一种情况:文件A.php中内容如下

<?php
class A{
  public function __construct(){
   echo 'fff';
  }
}
?>

文件C.php 中内容如下:

<?php
function __autoload($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
$a = new A(); //这边会自动调用__autoload,引入A.php文件
?>

第二种情况:有时我希望能自定义autoload,并且希望起一个更酷的名字loader,则C.php改为如下:

<?php
function loader($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register('loader'); //注册一个自动加载方法,覆盖原有的__autoload
$a = new A();
?>

第三种情况:我希望高大上一点,用一个类来管理自动加载

<?php
class Loader
{
public static function loadClass($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
}
spl_autoload_register(array('Loader', 'loadClass'));
$a = new A();
?>

当前为最佳形式。

通常我们将spl_autoload_register(*)放在入口脚本,即一开始就引用进来。比如下面discuz的做法。

if(function_exist('spl_autoload_register')){
  spl_autoload_register(array('core','autoload')); //如果是php5以上,存在注册函数,则注册自己写的core类中的autoload为自动加载函数
}else{
  function __autoload($class){ //如果不是,则重写php原生函数__autoload函数,让其调用自己的core中函数。
    return core::autoload($class);
  }
}

相关文章:

  • 2022-01-04
  • 2021-12-07
  • 2021-10-04
  • 2021-12-02
  • 2021-08-30
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2021-05-22
  • 2021-08-15
  • 2021-07-29
相关资源
相似解决方案