php - 如何将所有 php 类包含在一个文件中?

标签 php

这里的所有问题都涉及如何将文件导入到目录中,我正在寻找一种智能方法,允许我在单个类中导入所有类。具体来说,假设我有这样的结构:

\ 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个,导入所有内容会很痛苦。那么导入所有类并访问其函数的明智方法是什么?

最佳答案

我不太确定您为什么要这样做,但很容易做到:

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();

这是一个非常简单的自动加载器,但我希望您能理解它。

关于php - 如何将所有 php 类包含在一个文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35407473/

相关文章:

php - 带 nohup 的 Shell_exec php

php - 将IOS中加密的JSON数据发送给PHP解密

php - 根据对象的属性对数组进行排序

php - 如何在 php 中添加 while 循环创建的图像的链接?

php - laravel 5 中的 Multi-Tenancy 应用程序?

php - PHP 简单 IF 上的奇怪现象

php - 升级到 PHP 7 后 session 不起作用

php - Laravel 4 一对一关系

php - 将数组的特定元素传递给 joomla 3 模块中的 ajax

javascript - 将 PHP 关联数组转换为 json 对象