PHP类自动加载
使用 spl_autoload_register() 来注册你的自动加载函数
PHP 提供了很多方式来自动加载类文件。 比如 __autoload() 函数。 但这只能定义一个 __autoload() 函数,因此如果你的程序使用的库也包含 __autoload() 函数的话,就会发生冲突。
处理这个问题的正确方法是唯一地命名你的自动加载函数,然后使用 spl_autoload_register() 函数来注册它。 该函数允许定义多个 __autoload() 这样的函数,因此你不必担心其他代码的 __autoload() 函数。
点击查看代码
<?php
//存放类文件的基础目录
define('CLASS_BASE_PATHS', json_encode([
'./backend/models',
'./common/models',
]));
/*
定义自动加载类的函数
1、类存储文件夹根目录下的类加载:new Demo() -> 根目录/Demo.php
2、类存储文件夹子目录下的类加载:new Order_Detail() -> 根目录/order/Detail.php (下划线拆分子目录的方式)
*/
function autoloadClass($class){
$class_file = '';
if (strpos($class, '_')) {
$class_arr = explode('_', $class);
$class_arr_count = count($class_arr);
foreach ($class_arr as $i => $value) {
if ($i < $class_arr_count - 1) {
$class_file .= strtolower($value) . '/';
}else{
$class_file .= $value . '.php';
}
}
}else{
$class_file = $class . '.php';
}
$class_base_paths = json_decode(CLASS_BASE_PATHS, true);
foreach($class_base_paths as $base_path){
$file = $base_path . '/' . $class_file;
if (file_exists($file) && is_readable($file)) {
include_once($file);
return;
}
}
}
spl_autoload_register('autoloadClass');
$demo = new Demo();
$order_detail = new Order_Detail();
本文来自博客园,作者:Kim金,转载请注明原文链接:https://www.cnblogs.com/jxzCoding/articles/16046245.html