如何在一个文件中包含所有php类?
这里所有的问题都是关于如何将文件导入目录,我正在寻找一种智能的方法,允许我在一个类中导入所有类。具体来说,假设我有这样一个结构:如何在一个文件中包含所有php类?,php,Php,这里所有的问题都是关于如何将文件导入目录,我正在寻找一种智能的方法,允许我在一个类中导入所有类。具体来说,假设我有这样一个结构: \ Root 'Main folder Bootstrap.php 'This is the main class \System Core.php Language.php Helper.php include "System/Core.php"; include "System/Lan
\ Root 'Main folder
Bootstrap.php 'This is the main class
\System
Core.php
Language.php
Helper.php
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();
}
现在在Bootstrap.php
中,为了导入核心、语言、助手
类,我应该这样做:
\ Root 'Main folder
Bootstrap.php 'This is the main class
\System
Core.php
Language.php
Helper.php
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个,那么导入所有文件将是一件痛苦的事情。那么,导入所有类并访问它们的函数的智能方法是什么呢?我不太清楚您为什么要这样做,但很容易做到:
foreach(glob('System/*.php') as $file) include_once "System/$file";
可能您应该看看自动加载:
这是一个非常简单的自动加载器,但我希望您能了解它。您可以使用loop来实现这一点,您可以使用autoloadfunction@AmitRajput嗯,听起来不错,但是我应该为每个类创建一个对象吗?我从不使用自动加载功能如果你不想使用自动加载程序,你可以连接所有的类文件,只包含一个文件<代码>查找-名称'*.php'-not-name'lib.php'-exec cat{}+>lib.php(作为构建的一部分)。这将完全满足您的需要,但是使用名称空间和自动加载程序可以获得更好的解决方案。我建议阅读PSR0和PSR4,看看自动加载程序应该如何工作。
自动加载
帮助我避免为每个类创建对象实例?自动加载只是按照预定义的规则定位和加载文件。您仍然需要为要使用的每个类创建一个实例。spl\u autoload\u register
应该放在构造中?很高兴听到\uuuu DIR\uuu
在您的情况下起作用,但正确的路径在很大程度上取决于服务器环境和项目设置。