非常快的n00b问题,在PHP中我可以包含一个脚本目录.
即代替:
include('classes/Class1.php');
include('classes/Class2.php');
是这样的:
include('classes/*');
似乎找不到为特定类包含大约10个子类的集合的好方法.
Kar*_*ten 427
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
Mar*_*ius 50
这是我在PHP 5中包含来自几个文件夹的许多类的方法.这只有在你有类的情况下才有效.
/*Directories that contain classes*/
$classesDir = array (
    ROOT_DIR.'classes/',
    ROOT_DIR.'firephp/',
    ROOT_DIR.'includes/'
);
function __autoload($class_name) {
    global $classesDir;
    foreach ($classesDir as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once ($directory . $class_name . '.php');
            return;
        }
    }
}
Ban*_*ing 32
我意识到这是一个较旧的帖子但是......不要包括你的课程......而是使用__autoload
function __autoload($class_name) {
    require_once('classes/'.$class_name.'.class.php');
}
$user = new User();
然后每当你调用一个尚未包含的新类时,php将自动触发__autoload并为你包含它
小智 20
这只是对Karsten代码的修改
function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}
include_all_php("my_classes");
Sor*_*n C 18
2017年如何做到这一点:
spl_autoload_register( function ($class_name) {
    $CLASSES_DIR = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR;  // or whatever your directory is
    $file = $CLASSES_DIR . $class_name . '.php';
    if( file_exists( $file ) ) include $file;  // only include if file exists, otherwise we might enter some conflicts with other pieces of code which are also using the spl_autoload_register function
} );
这里的PHP文档推荐:自动加载类
你可以使用set_include_path:
set_include_path('classes/');
http://php.net/manual/en/function.set-include-path.php
| 归档时间: | 
 | 
| 查看次数: | 217582 次 | 
| 最近记录: |