sality
sality

Reputation: 51

PHP Codeigniter Variable Scope Error

I can't figure out why this code is outputting a Notice error

<?php

class Dashboard extends CI_Controller {   

    public $data = array();

    public function __construct() 
    {

        parent::__construct();
        $this->data['brand_title']   = 'Company Brand';

    }

    public function index()
    {
        echo $brand_title;
    }
}

I get a Undefined variable: brand_title error.

Upvotes: 0

Views: 197

Answers (3)

anon
anon

Reputation:

The $brand_title variable doesn't exist. That's why it's generating the Undefined variable error. If you want to store it in a variable and use that, try this:

 public function index()
 {
     $brand_title = $this->data['brand_title'];
     echo $brand_title;
 }

Upvotes: 0

Samy Massoud
Samy Massoud

Reputation: 4385

You can't use this like that in the same controller only in view of the same method you can use this

but if you want to use it like your post then it should be like that

echo $this->data['brand_title'];

Upvotes: 0

Terry Harvey
Terry Harvey

Reputation: 840

You can access it like this:

echo $this->data['brand_title'];

If you prefer your way, you could do it like this:

extract($this->data);
echo $brand_title;

But extract() is generally considered bad practice.

Upvotes: 3

Related Questions