2012-04-18 26 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'];