2011-08-14 33 views
12

是否可以在类中包含带有php变量的文件?那么如何才能最好地访问全班的数据呢?php包含文件中的类

我一直在Google上搜索一段时间,但没有一个例子有效。

谢谢 Jerodev

+1

你能多一些扩大你想做什么? –

+2

请指出为什么没有http://stackoverflow.com/search?q=include+file+in+class+php回答你的问题。 – Gordon

+0

这样做似乎是不可能的,所以我将使用xml来加载外部数据。 – Jerodev

回答

13

最好的办法就是加载它们,不包括他们通过外部文件

如:

// config.php 
$variableSet = array(); 
$variableSet['setting'] = 'value'; 
$variableSet['setting2'] = 'value2'; 

// load config.php ... 
include('config.php'); 
$myClass = new PHPClass($variableSet); 

// in class you can make a constructor 
function __construct($variables){ // <- as this is autoloading see http://php.net/__construct 
    $this->vars = $variables; 
} 
// and you can access them in the class via $this->vars array 
1

其实,你应该将数据追加到变量。

<?php 
/* 
file.php 

$hello = array(
    'world' 
) 
*/ 
class SomeClass { 
    var bla = array(); 
    function getData() { 
     include('file.php'); 
     $this->bla = $hello; 
    } 

    function bye() { 
     echo $this->bla[0]; // will print 'world' 
    } 
} 

?>

1

从性能的角度来看,这将是更好,如果你会使用.ini文件来存储您的设置。

[db] 
dns  = 'mysql:host=localhost.....' 
user  = 'username' 
password = 'password' 

[my-other-settings] 
key1 = value1 
key2 = 'some other value' 

然后在你的类,你可以做这样的事情:

class myClass { 
    private static $_settings = false; 

    // this function will return a setting's value if setting exists, otherwise default value 
    // also this function will load your config file only once, when you try to get first value 
    public static function get($section, $key, $default = null) { 
     if (self::$_settings === false) { 
      self::$_settings = parse_ini_file('myconfig.ini', true); 
     } 
     foreach (self::$_settings[$group] as $_key => $_value) { 
      if ($_key == $Key) return $_value; 
     } 
     return $default; 
    } 

    public function foo() { 
     $dns = self::get('db', 'dns'); // returns dns setting from db section of your config file 
    } 
}