2011-08-14 9 views
12

クラス内にphp変数を含むファイルを含めることはできますか?そして、クラス全体のデータにアクセスするには、どのように最善の方法がありますか?クラス内のPHPインクルードファイル

私はこれをしばらく検索していましたが、例は一度も機能しませんでした。

は、例えば

外部ファイルを経由して、それらを含まないよう、最善の方法は、それらをロードすることで、 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 
    } 
} 
関連する問題