2012-04-18 2 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']; 
관련 문제