Welcome Guest, Not a member yet? Register   Sign In
Help with visibility of variables in parent/child models
#1

[eluser]Genki1[/eluser]
Hi,

Problem: From a child model, why can't I access a public variable declared in the parent model?

Details:
My controller Convert loads the model Parent_model which, in turn, loads model Child_model. Child extends Parent. Why is a variable declared public in the Parent_model not visible the in Child_model?

I'm using CI 2.0.2, PHP 5.2.17

Example:

Code:
class Convert extends CI_Controller {

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

  function start_here()
  {
    $this->load->model('Parent_model');
    $this->Parent_model->do_parent_stuff();  // execute a function in the parent model
  }

}
Code:
class Parent_model extends CI_Model {

  # variables declared public or static should be available to the child class
  public $my_public;
  public static $my_static = 'I am static';

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

  function do_parent_stuff()
  {
    $this->my_public = 'I am public';  // set the value of the public variable
    $this->load->model('Child_model');
    $this->Child_model->do_child_stuff();   // execute a function in the child model
  }

}
Code:
class Child_model extends Parent_model {

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

  function do_child_stuff()
  {
    # Get info from the variables
    echo parent::$my_static;  // correctly displays "I am static"
    echo property_exists('Parent_model', 'my_public');  // correctly displays "1"(True)
    echo $this->my_public;  // DISPLAYS NOTHING!  HUH?
  }

}

So, why doesn't $my_public echo "I am public"?

#2

[eluser]Narf[/eluser]
Because you're creating a new instance of it where my_public was never set.
#3

[eluser]Genki1[/eluser]
Thanks for your reply.

The value is set just before the child model is called and, in the child model, the function property_exists() reports True, so I don't understand your answer. Would you explain a bit more?

Code:
$this->my_public = 'I am public';  // set the value of the public variable
#4

[eluser]Matalina[/eluser]
In order for the I am public to be called you have to call the method do_parent_stuff on the Child model.

By creating a Child you are creating a new Parent with it. If you want to set all things the same you need to put the do_parent_stuff in the constructor of the Parent or the Child depending on who you want to say I am public.
#5

[eluser]Genki1[/eluser]
Thank you both for your helpful replies. I made the adjustments and now it works! :-)




Theme © iAndrew 2016 - Forum software by © MyBB