PHP Sibling Class Inheritance

342 views Asked by At

I'm a bit confused on whether or not this is possible. I've checked a couple of posts here on SO and they don't really explain what I'm looking for.

I have 3 classes. One main class and two classes extending that main class. (see code below). Is it possible to run a method in one of the two extended classes from it's sibling (the other extended class)?

If it's not possible, how can I change my code to accomplish what I'm doing in the example below?

DECLARATION

class A {

  public function __construct() {
     //do stuff
  }

}

class B extends A {

  private $classb = array();

  public function __construct() {
     parent::__construct();
     //do stuff
  }

  public function get($i) {
                return $this->classb[$i];
  }

  public function set($i, $v) {
    $this->classb[$i] = $v;
  }

}

class C extends A {

  public function __construct() {
    parent::__construct();
    //do stuff
  }

  public function display_stuff($i) {
    echo $this->get($i);  //doesn't work
    echo parent::get($i);  //doesn't work
  }
}

USAGE

$b = new B();
$c = new C();

$b->set('stuff', 'somestufftodisplay');
$c->display_stuff('stuff');   //   <----- Displays nothing.
1

There are 1 answers

7
jeroen On BEST ANSWER

Your code shows an additional problem apart from the main question so there are really two answers:

  1. No, you cannot run a method from a sibling class in another sibling class. If you need that, the method should be in the parent class. The same applies to properties.
  2. You cannot use the value of a property from one object in another object, even if they are both of the same class. Setting a property value in one object sets its value only there as different objects can have the same properties with completely different values. If you need to share the value of a property between the objects and also be able to modify it, you should use a static property. In this case you would have to define that in the parent class, see my previous point.

So to make it work, you would need something like

class A {

  private static $var = array();

  public function get($i) {
     return self::$var[$i];
  }

  public function set($i, $v) {
     self::$var[$i] = $v;
  }
}

class B extends A {

}

class C extends A {

  public function display_stuff($i) {
    echo $this->get($i); // works!
  }
}

$b = new B();
$c = new C();

$b->set('stuff', 'somestufftodisplay');
$c->display_stuff('stuff');

An example.