Sibling PHP Class Inheritance
I am a little confused as to whether this is possible. I checked several 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 extend this main class. (see code below). Is it possible to run a method in one of the two extended classes from it - sibling (the other extended class)?
If this is not possible, how can I modify my code to accomplish what I am 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
}
}
USING
$b = new B();
$c = new C();
$b->set('stuff', 'somestufftodisplay');
$c->display_stuff('stuff'); // <----- Displays nothing.
+3
source to share
1 answer
Your code shows an additional problem besides the main question, so there are two answers:
- No, you cannot run a method from the sibling class in another sibling class. If you need this, the method must be in the parent class. The same goes for properties.
- You cannot use a property value from one object in another object even if they are both of the same class. Setting the value of a property in one object only sets its value there, since different objects can have the same properties with completely different values. If you need to share the value of a property between objects and also be able to modify it, you must use a static property . In this case, you will need to define that in the parent class see my previous point.
To make it work, you will 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');
+2
source to share