-1

I've added "header_model" into codeigniter's autoload.php file. now its:

$autoload['model'] = array("header_model");

And i also can successfully use $this->header_model in other controllers.

But can't use it in MY_Loader class, which is extension of CI_Loader.

Example: Pages controller located at application/controllers/:

class Pages extends CI_Controller {

    public function view($page = 'home')
    {
      var_dump($this->header_model->get_menus()); //echoes data from database.
    }

}

MY_Loader class (located at application/core/ folder):

<?php
   class MY_Loader extends CI_Loader {

   function __construct()
   {
       parent::__construct();
   }

   public function template($template_name, $vars = array(), $return = FALSE)
   {

       $menuArray = $this->header_model->get_menus(); //echoes errors
       //like: Undefined property: MY_Loader::$header_model
       $vars["menuArray"] = $menuArray;
   }
}

Thanks for any help.

tereško
  • 58,060
  • 25
  • 98
  • 150
Nick
  • 455
  • 9
  • 28

1 Answers1

1

The problem is that $this is two different objects in Pages and MY_Loader.

Autoloaded classes, including models, wind up being variables in the controller. So $this->->header_model... works within Pages because it is a controller. But the object $this inside the function template is the instance of the MY_Loader class. And that class has no variable called header_model.

In order to reference the controller use get_instance(). Here's how

public function template($template_name, $vars = array(), $return = FALSE)
{

    $CI =& get_instance();
    $menuArray = $CI->header_model->get_menus(); //echoes errors
    //like: Undefined property: MY_Loader::$header_model
    $vars["menuArray"] = $menuArray;
}

Not part of your problem but I'd like to point out that you do not need the __construct() function in MY_Model. If a child class does not do any initialization in a constructor there is no need to create a constructor only to call parent::__construct();. PHP will find the parent class constructor execute it automatically.

DFriend
  • 8,869
  • 1
  • 13
  • 26