2011-08-14 46 views
12

Có thể bao gồm tệp có biến php bên trong lớp không? Và làm cách nào tốt nhất để tôi có thể truy cập dữ liệu bên trong cả lớp?php bao gồm tệp trong lớp

Tôi đã googling điều này một lúc, nhưng không có ví dụ nào hiệu quả.

Cảm ơn bạn, Jerodev

+1

Bạn có thể mở rộng một số chi tiết về những gì bạn muốn làm gì? –

+2

và vui lòng chỉ ra lý do tại sao không có http://stackoverflow.com/search?q=include+file+in+class+php nào trả lời câu hỏi của bạn. – Gordon

+0

Có vẻ như không thể thực hiện được điều này, vì vậy tôi sẽ sử dụng xml để tải dữ liệu ngoài. – Jerodev

Trả lời

13

cách tốt nhất là để tải chúng, không bao gồm chúng thông qua tập tin bên ngoài

ví dụ:

// 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

Trên thực tế, bạn nên thêm dữ liệu vào biến .

<?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

Từ quan điểm thực hiện xem, nó sẽ tốt hơn nếu bạn sẽ sử dụng tập tin .ini để lưu trữ các thiết lập của bạn.

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

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

Và sau đó trong lớp học của bạn, bạn có thể làm một cái gì đó như thế này:

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 
    } 
}