2011-08-14 8 views
12

클래스 내에 PHP 변수가있는 파일을 포함 할 수 있습니까? 전체 클래스의 데이터에 액세스 할 수있는 가장 좋은 방법은 무엇입니까?php 클래스에 포함 된 파일

나는 잠시 동안이 문제를 조사해 왔지만 그 중 어떤 사례도 효과가 없었다.

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

당신은 당신이 원하는 무슨에 좀 더 확장 할 수 있습니까? –

+2

그리고 http://stackoverflow.com/search?q=include+file+in+class+php에 질문에 대한 답변이없는 이유를 알려주십시오. – Gordon

+0

이렇게하는 것은 꽤 불가능한 것처럼 보이므로 xml을 사용하여 외부 데이터를로드합니다. – Jerodev

답변

13

을 주셔서 감사합니다,

는 예를 들어 외부 파일을 통해이를 포함하지 .

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

사실, 당신은 변수에 데이터를 추가해야합니다

이 Jerodev 가장 좋은 방법은 그들을로드하는 것입니다

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 
    } 
} 
관련 문제