2013-09-21 151 views
0

我試圖創建一個配置類,所以我可以輕鬆地編輯我的網站信息。我的所有配置都保存在一個php(不是.inc)文件中,但我似乎無法從我的Config.php類訪問它。我錯過了什麼?包含文件到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 /> 
+0

您可以嘗試使用'__DIR__' – JTC

+0

不可以。我得到了'
警告:include(__ DIR __/../../conf.php):無法打開流:沒有這樣的文件或目錄在D:\ xampp \ htdocs \ sunrise \ sunrise.app \ Classes \日出\ CONFIG.PHP上線

警告:包括():失敗開口 '__DIR __/../../conf.php' 列入(include_path中=」; d:\ XAMPP \ PHP \ PEAR')in D:\ xampp \ htdocs \ sunrise \ sunrise.app \ Classes \ Sunrise \ Config.php on line
' – enchance

回答

0

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' 
} 
+0

它工作正常!我猜測問題是使用'ob_ *'函數? – enchance

+0

這裏沒有效果。實際上它們是無用的。當你在配置文件中使用'return'時,你所要做的就是將它分配給一些變量。 –

+0

這是完美的! – enchance