Welcome Guest, Not a member yet? Register   Sign In
Creating data in constructor
#1

[eluser]bertcarremans[/eluser]
Hi,

I've been looking around in the forum to find a solution for my problem, but I could not find anything.

I want to do the following in the constructor function

Code:
function Site() {
        parent::Controller();
        session_start();

        $data = array();
        $this->data['last_models'] = $this->M_model->getLastModels();
    }

And then later use it in a controller function home

Code:
function home() {
        // Some code here ...

        $data['last_models'] = $this->$data['last_models'];
        
        // Some code here ...

    }

Unfortunately, I get the following error

Code:
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Is it not possible to use the (auto-loaded) model M_model in the constructor function?

Thanks!
#2

[eluser]mdvaldosta[/eluser]
Try putting var $data as a class variable, so that when you use $this your referring to something.
#3

[eluser]bertcarremans[/eluser]
Thanks mdvaldosta,

but do you mean with putting $data as a class variable that I have to state

Code:
public $data;

at the top of the Controller class? If yes, I already tried this, but it does not work.
Could it perhaps be that in the home function I also add extra information to the $data array?

Code:
function home() {
        // Some code here ...

        // Data array
        $data = array(
            'title'=>'This is the title',
            'pagina'=>'home'
        );

        // Some code here ...
    }

Does this adding of extra information overwrite the $data array created in the constructor?

Thanks!
#4

[eluser]Twisted1919[/eluser]
Usually, when using $this->data, you do it when you have a MY_Controller and extend your controllers from it, assuming that in your MY_Controller, you set information in $this->data that will be globally available in other controller that extends it.

If you don't have a MY_Controller, then you can go like
Code:
class Site extends Controller{

   public $last_models;

   public function __construct()
   {
     parent::Controller();
     $this->last_models = $this->ANY_GLOBAL_MODEL->ANY_METHOD_WITHIN_MODEL();
     // now, accessing $this->last_models in each of your class methods will give you the expected result.
   }

   public function home()
   {
        $data = array(
            'title'=>'This is the title',
            'pagina'=>'home'
        );
      // you can do like this :
      $data['last_models'] = $this->last_models;
  
      //or, if you have many properties and you are lazy like i am
      $data = array_merge($data,get_object_vars($this));
      

      // in both cases, if accessing $last_models in the view, will give you the correct result.
   }
}
#5

[eluser]bertcarremans[/eluser]
Excellent! Works perfect. Thanks a lot Twisted1919




Theme © iAndrew 2016 - Forum software by © MyBB