php spl_autoload_register

spl_autoload_register  可以同时注册多个自动加载函数。

./kang/H.class.php

<?php


class H {

}

./kang/kang.php

<?php
function kangAutoload($class_name) {
echo 'kangAutoload<br>';
// 先判断当前所需要加载的类,是否为当前模块的
$class_list = array('H', 'Z', 'K');
if (in_array($class_name, $class_list)) {
require './kang/' . $class_name . '.class.php';
}
}
spl_autoload_register('kangAutoload');

./user/U.class.php

<?php


class U {

}

./user/user.php

<?php

function userAutoload($class_name) {
echo 'userAutoload<br>';
require './user/' . $class_name . '.class.php';
}
spl_autoload_register('userAutoload');

./oop_9.php

<?php


// 模块kang
// 载入模块kang.php 核心文件
require './kang/kang.php';

$o = new H;
var_dump($o);

echo '<br>';
// 模块user
require './user/user.php';
$b = new U; //当有两个require 的时候,会按照定义的require的先后顺序,逐次的进入
// ~~~~~~~~复制的kang.php <?php
// function kangAutoload($class_name) {
// echo 'kangAutoload<br>';
// 先判断当前所需要加载的类,是否为当前模块的
// $class_list = array('H', 'Z', 'K');
// if (in_array($class_name, $class_list)) {
// require './kang/' . $class_name . '.class.php';
// }
// }
// spl_autoload_register('kangAutoload');~~~~~~~~
var_dump($b);


// kangAutoload// 页面的结果:var_dump($o)的结果
// object(H)#1 (0) { } // 页面的结果:var_dump($o)的结果


// kangAutoload//页面的结果:$b = new U; 先去kang里面找,不满足if (in_array($class_name, $class_list))
// userAutoload //页面的结果:$b = new U 去./user/user.php里面找
// object(U)#2 (0) { } //页面的结果:$b = new U

原文地址:https://www.cnblogs.com/huodaihao/p/7072514.html