S
S
Sergey2020-11-04 17:17:18
PHP
Sergey, 2020-11-04 17:17:18

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();


In the get() method of class A, we have changed the $age property to 10, but this change is ignored when called. What if I use static properties, everything works out

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey delphinpro, 2020-11-04
@sergik15828

$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

T
ThunderCat, 2020-11-04
@ThunderCat

In the get() method of class A, we changed the $age property to 10, but this change is ignored when called.

1) How did you find out? )
2) You are confusing the concepts of class and object (class instance).

F
FanatPHP, 2020-11-04
@FanatPHP

vrrcvqiy17x51.png
Just a picture in the subject. Almost.
$b is a completely separate object that doesn't know anything about what's going on in $a

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question