0

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?

2 Answers 2

2

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'];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.