这里的所有问题都涉及如何将文件导入目录,我正在寻找一种允许我在单个类中导入所有类的智能方法。具体来说,假设我有这样的结构:
\ Root 'Main folder
Bootstrap.php 'This is the main class
\System
Core.php
Language.php
Helper.php
现在在Bootstrap.php
导入Core, Language, Helper
类我应该这样做:
include "System/Core.php";
include "System/Languages.php";
include "System/Helper.php;"
private $_core;
private $_languages;
private $_helper;
public function __construct()
{
$this->_core = new Core();
$this->_languages = new Languages();
$this->_helper = new Helper();
}
假设文件超过20个,导入所有内容都会很痛苦。那么导入所有类并访问其功能的智能方法是什么?
答案 0 :(得分:5)
我不确定你为什么要那样做,但很容易做到:
foreach(glob('System/*.php') as $file) include_once "System/$file";
您可以查看自动加载:http://php.net/manual/en/language.oop5.autoload.php
// Register autoloader
spl_autoload_register(function ($class_name) {
$fullPath = 'System/' . $class_name . '.php';
if(file_exists($fullPath)) include $fullPath;
});
// Simply create a new object, class will be included by autoloader
$helper = New Helper();
这是一个非常简单的自动加载器,但我希望你能理解它。