Zoran
Zoran

Reputation: 1371

how can i pass data from parent controller in codeigniter

I am trying to prevent myself from repeating the same code over and over in every controller. So i place function that fetch the data in the parent controller, and i am trying to pass that data in the child controller.

class Frontend_Controller extends MY_Controller
{
    public function __construct() 
    {
        parent::__construct();  
        $this->load->model('configOptionsModel');
    $this->db->where('configid = "2"');
        $specialdata['bgimage'] = $this->configOptionsModel->get();       
    }    
}

Here is the code for the child controller

 class Home extends Frontend_Controller {

public function __construct() {
        parent::__construct(); 
        print_r($this->specialdta); // line where error occurs
        die();
    }

    public function index()
{   
    $data['main_content'] = 'home';
    $this->load->view('frontEnd/template',$data);   
}   
 }

I get the following error:

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Home::$specialdta
Filename: controllers/home.php
Line Number: 9

Sure enough, line 9 is: print_r($this->specialdta);

I know that if you extends a controller (class), you have access to the methods and properties from the parent controller (classs), since they are declared public.

Can anyone explain me what i am doing wrong?

Regards,Zoran

Upvotes: 1

Views: 2575

Answers (1)

Jordan Arsenault
Jordan Arsenault

Reputation: 7388

CodeIgniter is not magic and follows PHP class specifications and rules. Like any inheritance model, to access variables from a parent class, you must assign them to $this in the parent.

$this->specialdata = $this->configOptionsModel->get(); in the parent constructor will work for you, but beware of assigning data attributes wildly like this. Under the hood, and many classes down the inheritance chain, CodeIgniter's core may have some common properties reserved and you don't want to overwrite them.

Upvotes: 1

Related Questions