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

我哪里出错了,有没有更简单的方法来获得相同的结果?

4

2 回答 2

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'];
于 2012-04-18T03:51:03.297 回答
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'];
于 2012-04-18T03:52:39.583 回答