Answer the question
In order to leave comments, you need to log in
Accessing a modified property of a parent class?
I apologize for a possibly stupid question, I'm just starting to learn OOP.
class A {
protected $age = 5;
public function get() {
$this->age = 10;
$b = new B();
}
}
class B extends A {
public function __construct() {
echo $this->age;
}
}
$a = new A();
$a->get();
Answer the question
In order to leave comments, you need to log in
$b = new B();
You have created a new class instance. Its initial value is 5. And the property was changed for an already existing instance.
In addition, the get method is overridden in class B, and calling $b->get() will always return the initial value.
Keep studying. So far there is no understanding.
If you need to pull the parent method
class A {
protected $age = 5;
public function get() {
$this->age = 10;
}
}
class B extends A {
public function get() {
parent::get();
echo $this->age;
}
}
$obj = new B();
$obj->get(); // 10
In the get() method of class A, we changed the $age property to 10, but this change is ignored when called.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question