这是代码:
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
我哪里出错了,有没有更简单的方法来获得相同的结果?
答案 0 :(得分: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'];
答案 1 :(得分: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'];