在我的PHP项目中,所有的类文件都包含在一个名为“class”的文件夹中。每个类都有一个文件,随着越来越多的功能被添加到应用程序中,类文件夹变得越来越大,组织得越来越少。现在,这段代码,在初始化文件中,为应用程序中的页面自动添加类:
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';});
如果要将子文件夹添加到现有的“类”文件夹中,以及在这些子文件夹中组织的类文件,那么是否有一种方法可以修改自动加载代码,使其仍然工作?
例如-假设类文件夹中的子文件夹如下所示:
发布于 2014-02-01 14:48:00
我发现您查看PSR标准的网址是:http://www.php-fig.org
此外,本教程将帮助您为自己构建和理解一个。http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
获取所有子文件夹的代码片段:
function __autoload($className) {
$extensions = array(".php", ".class.php", ".inc");
$paths = explode(PATH_SEPARATOR, get_include_path());
$className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
foreach ($paths as $path) {
$filename = $path . DIRECTORY_SEPARATOR . $className;
foreach ($extensions as $ext) {
if (is_readable($filename . $ext)) {
require_once $filename . $ext;
break;
}
}
}
}发布于 2017-11-23 23:48:14
我的解决方案
function load($class, $paste){
$dir = DOCROOT . "\\" . $paste;
foreach ( scandir( $dir ) as $file ) {
if ( substr( $file, 0, 2 ) !== '._' && preg_match( "/.php$/i" , $file ) ){
require $dir . "\\" . $file;
}else{
if($file != '.' && $file != '..'){
load($class, $paste . "\\" . $file);
}
}
}
}
function autoloadsystem($class){
load($class, 'core');
load($class, 'libs');
}
spl_autoload_register("autoloadsystem");发布于 2018-04-08 07:53:20
根部
是-..。
src//类目录
-src/数据库
-src/Database.php //数据库类
--src/登录
-src/Login.php // Login类
应用程序//应用程序目录
-app/index.php
-index.php
应用程序文件夹中的index.php代码可以自动从src文件夹中自动加载所有类。
spl_autoload_register(function($class){
$BaseDIR='../src';
$listDir=scandir(realpath($BaseDIR));
if (isset($listDir) && !empty($listDir))
{
foreach ($listDir as $listDirkey => $subDir)
{
$file = $BaseDIR.DIRECTORY_SEPARATOR.$subDir.DIRECTORY_SEPARATOR.$class.'.php';
if (file_exists($file))
{
require $file;
}
}
}});根文件夹中的index.php代码可以自动从src文件夹中自动加载所有类。
更改变量$BaseDIR,
$BaseDIR='src';https://stackoverflow.com/questions/21499387
复制相似问题