EllisLab text mark
Advanced Search
     
Problem whit inheritance, what happened?
Posted: 21 October 2012 07:31 AM   [ Ignore ]
Joined: 2010-11-17
2 posts

hi,

I have a doubt. ¿Someone Help me? smile

Let’s go. I have these class:

class myclass_a(){

  
protected $at1;

  function 
get_at1(){
    $this
->get_at1;
  
}

  
function set_at1($at1){
    $this
->at1=$at1;
  
}
}

class myclass_b extends a{
..
}

class myclass_c extends a{
..

In my controller:

$this->load->library(array('class_a','class_b','class_c'));

$this->class_b->set_at1('hello');
echo 
$this->class_b->get_at1();  //show 'hello', is correct

echo $this->class_c->get_at1();   //show empty, fail! 


why the second call is empty?. I think that I have one instance of class_a. If I modify his attributes from class_b or class_c, Should not I always have the same value from get_at1() in class_a?

Thanks.

 

 
Posted: 21 October 2012 09:19 AM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Joined: 2012-10-17
27 posts

Each time you instantiate one of these objects, you are allocating a completely isolated space in memory. These spaces in no way reference one another, so changes made to one object will not be reflected in another.

While I’m not entirely sure what you are trying to accomplish, you will most likely want to look into pointers or assigning variables by reference. Instead of creating two isolated spaces in memory, pointers or assigning variables by reference allows for one space in memory so that changes made to either are reflected in both.

 
Posted: 21 October 2012 10:25 AM   [ Ignore ]   [ # 2 ]   [ Rating: 0 ]
Joined: 2010-11-17
2 posts
benton.snyder - 21 October 2012 09:19 AM

Each time you instantiate one of these objects, you are allocating a completely isolated space in memory. These spaces in no way reference one another, so changes made to one object will not be reflected in another.

While I’m not entirely sure what you are trying to accomplish, you will most likely want to look into pointers or assigning variables by reference. Instead of creating two isolated spaces in memory, pointers or assigning variables by reference allows for one space in memory so that changes made to either are reflected in both.

Thanks very much benton.snyder,

Indeed I want instances by reference. Is it possible to do this using CI structure?, Is it possible to get through load-> library?.

any suggestions?

Tnks.

 
Posted: 22 October 2012 11:07 AM   [ Ignore ]   [ # 3 ]   [ Rating: 0 ]
Joined: 2012-10-17
27 posts

This would be outside the scope of CI but still quite easy.

$class_a = new myclass();
$class_b = &$class_a

Now changes made to either class_a or class_b will be reflected in both as they both point to the same area in memory.

Please see http://php.net/manual/en/language.references.php for more information.