将文件包含到PHP类中

魅力

我正在尝试创建一个Config类,以便可以轻松编辑我的站点信息。我所有的配置都保存在一个php(不是.inc)文件中,但是我似乎无法从我的Config.php班级访问它我想念什么?

// My folders
sunrise.app
    - conf.php
    - Classes\Sunrise\Config.php
public
    - sample.php

我的配置文件:

// conf.php
return array(
    'sample' => 'Foo'
);

这是我的课:

// Classes\Sunrise\Config.php
namespace Classes\Sunrise;
class Config {

    private static $config;

    public static function setup() {
        ob_start();
        include '../sunrise.app/conf.php';
        self::$config = ob_get_contents();
        ob_end_clean();
    }

    public static function all() {
        return self::$config;
    }

}

我对自动加载的使用效果很好,所以这不是问题。我唯一无法获得的是,当我运行Config::all()所有获得的信息时,是NULL一个空字符串或一条错误消息。我想念什么?

// Sample php file
use Classes\Sunrise\Config;

Config::setup();
echo print_r(Config::all());

更多的:

我试着尝试其中的路径,include但仍然没有:

  • conf.php
  • ../conf.php
  • ../../conf.php
  • ../sunrise.app/conf.php

我有时会收到此错误

<br /> <b>Warning</b>: include(../../conf.php): failed to open stream: No such file or directory in <b>D:\xampp\htdocs\sunrise\sunrise.app\Classes\Sunrise\Config.php</b> on line <b>9</b><br /> <br /> <b>Warning</b>: include(): Failed opening '../../conf.php' for inclusion (include_path='.;D:\xampp\php\PEAR') in <b>D:\xampp\htdocs\sunrise\sunrise.app\Classes\Sunrise\Config.php</b> on line <b>9</b><br />
希普卢·莫卡丁

dirname(__FILE__).'../../conf.php' 应该管用。

请注意,如return在配置文件中使用的那样,请确保将返回值include赋给变量。

$conf = include dirname(__FILE__).'../../conf.php'

ob_*根本不需要功能。因为配置文件不输出任何内容。它只是执行代码。因此,以下setup方法就足够了。

 public static function setup() {
    self::$config = include dirname(__FILE__).'../../conf.php'
 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章