php之自动加载autoload

当程序的代码运行到需要加载某个类的时候,php内部机制可以做到自动加载该类文件。

1. __autoload($class)

__autoload尝试加载未定义的类 。
./class/A.class.php

<?php
 class A{

    function __construct(){

        echo "<BR> A中的构造方法";
    }
 }

?>

./autoload.php

<?php

header("content-type:text/html;charset=utf-8");

function  __autoload ($name){
  echo "<br> __autoload::".$name;
  $file  = "./class/".$name.".class.php";

  if(file_exists($file)){
    require_once $file;
  }
}

//创建A类对象,需要把A类加载进来
$a = new A();

?>

这里写图片描述

2.spl_autoload_register

spl_autoload_register — 注册给定的函数作为 __autoload 的实现 。
./class/A.class.php

<?php
 class A{

    function __construct(){

        echo "<BR> A中的构造方法";
    }
 }

?>

./lib/B.class.php

<?php
 class B{

    function __construct(){

        echo "<BR> B中的构造方法";
    }
 }

./autolaod.php

<?php

header("content-type:text/html;charset=utf-8");

function  __autoload ($class){
  echo "<br> __autoload::".$class;
  $file  = "./class/".$class.".class.php";

  if(file_exists($file)){
    require_once $file;
  }
}


//注册给定的函数作为 __autoload 的实现 
spl_autoload_register('my_autoload_1');


function my_autoload_1($class){
echo "<br> my_autoload_1::".$class;
  $file  = "./lib/".$class.".class.php";
    if(file_exists($file)){
    require_once $file;
  }

}

//采用匿名函数的方式注册
spl_autoload_register(function($class){
  echo "<br> 匿名函数自动加载::".$class;
  $file  = "./class/".$class.".class.php";
  if(file_exists($file)){
    require_once $file;
  }

});


//创建A类对象,需要把A类加载进来
$a = new A();

class C extends B{};

$c = new C();


// my_autoload_1::D
// 匿名函数自动加载::D
// Fatal error: Class 'D' not found in C:\Apache24\htdocs\day16\auload.php on line 45
$d = new D();//依次寻找注册的自动加载方法,都失败了,报错!

?>

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值