enloz
enloz

Reputation: 5824

Notice: Undefined index: in class->array

This is the code:

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'];

And I get this error:

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

Where have I gone wrong, and is there any simpler way to get same result?

Upvotes: 0

Views: 1243

Answers (2)

Mike Purcell
Mike Purcell

Reputation: 19979

You are in the wonderful world of OOP, no longer do you have to use global!

Try this:

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'];

Upvotes: 2

bfavaretto
bfavaretto

Reputation: 71908

You are populating a separate global variable instead of the object properties. Use $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'];

Upvotes: 2

Related Questions