2012-04-18 14 views
0

これはコードです:お知らせ:未定義のインデックス:クラス - に>配列

class app { 
    public $conf = array(); 
    public function init(){ 
     global $conf; 
     $conf['theme'] = 'default'; 
     $conf['favicon'] = 'favicon.ico'; 
    } 
    public function site_title(){ 
     return 'title'; 
    } 
} 

$app = new app; 
$app->init(); 


//output 
echo $app->conf['theme']; 

そして、私はこのエラーを取得:私が間違っている

Notice: Undefined index: theme in C:\xampp\htdocs\...\trunk\test.php on line 21 

を、そして任意の簡単な方法があります同じ結果を得るには?

答えて

2

あなたはOOPの素晴らしい世界にいる、もはやあなたはglobalを使用する必要はありません!

これを試してみてください:

class app 
{ 
    public $conf = array(); 

    // Notice this method will be called every time the object is isntantiated 
    // So you do not need to call init(), you can if you want, but this saves 
    // you a step 
    public function __construct() 
    {  
     // If you are accessing any member attributes, you MUST use `$this` keyword 
     $this->conf['theme'] = 'default'; 
     $this->conf['favicon'] = 'favicon.ico'; 
    } 
} 

$app = new app; 

//output 
echo $app->conf['theme']; 
2

オブジェクトプロパティの代わりに別のグローバル変数を設定しています。 $thisを使用します。

class app { 
    public $conf = array(); 
    public function init(){ 
     $this->conf['theme'] = 'default'; 
     $this->conf['favicon'] = 'favicon.ico'; 
    } 
    public function site_title(){ 
     return 'title'; 
    } 
} 
$app = new app; 
$app->init(); 

//output 
echo $app->conf['theme']; 
関連する問題