Merging Properties

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
slogger2
Forum Newbie
Posts: 1
Joined: Sat Jan 31, 2009 8:57 pm

Merging Properties

Post by slogger2 »

I am interested in merging an array made in a parent class with an array made in its child class. For example:

Code: Select all

 
class A {
 
  var $something = array(1,2,3);
 
}
 
class B extends A {
 
  var $something = array(4,5,6);
 
}
 
 
At this point, I want B::something to be equal to array(1,2,3,4,5,6). I know this seems useless in a setup such as this, but imagine that there are functions in class A that do something with $something (which would include both the values set in class A and in its children). Better yet, imagine that A actually extends another object which holds this function, ie:

Code: Select all

 
 
class P {
 
  abstract var $something;
 
  function show() {
 
    foreach($this->something as $thing) {
 
      echo $thing . " ";
 
    }
 
  }
 
}
 
class A extends P {
 
  var $something = array(1,2,3);
 
}
 
class B extends A {
 
  var $something = array(3,4,5);
 
}
 
$myVar = new B();
 
$myVar->show(); // expected output: 1 2 3 4 5 6 
 
 
Is this possible? I think it should be, because in the CakePHP framework, some variables (such as $uses) displays this functionality and I haven't figured out how.

Thanks a bundle in advance.
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: Merging Properties

Post by novice4eva »

Since you are overriding the parents property the end result you will get is the one you set in the lowest child class. You can create a new variable for child class and then append the parent class's attributes to it in the constructor or vice versa. Something like

Code: Select all

 
class B extends A {
 
  protected $mysomething = array(3,4,5);
 public function B()
{
    $this->something = array_merge($this->something ,$this->mysomething);//overrides parents prop
   $this->mysomething = array_merge($this->something ,$this->mysomething);//adds parents prop
}
}
 
EDIT : abstract var $something;//I don't think this is valid, well never used it !!
Post Reply