class Main{ function make(){ echo "a - " . $this->a . "<br>"; echo "b - " . $this->b . "<br>"; // как сделать так, чтобы здесь были доступны переменные $a и $b? Возможно ли это вообще? } } class Child extends Main{ protected $a = "A"; } class ChildLast extends Child{ protected $b = "B"; } $obj = new Main(); // при этом объект создается именно для родителя(Main) $obj->make(); 

    3 answers 3

    You can get data from the parent class, because when defining a child class, we specify (link, generate from it) another class.
    The parent has absolutely no data on how many children he has and if there is any (yes, yes, such a bad parent ...), so there is no access to the child classes.

    In any case, the code that uses such communications should lie here .
    As a solution, call the parent function in the descendants, and transfer the necessary data with arguments.
    Truth then it will be possible to use the data of only one class - the one who caused.

      Not. Main, Child, ChildLast three different objects. In addition, you are trying to pull the object in the opposite direction from the destination. All that is described in the Parent class is available in the child, but not vice versa.

        Captain Obviously kindly suggests - if the heir members are well desperately needed in the parent, then they (surprise-surprise) need to be moved from the heir to the ancestor. This is called "refactoring", and specifically this technique - "Raising the field"

        Or you can make the Main function abstract / virtual and implement / redefine with the necessary functionality in the heir.