Skip to content
Advertisement

How do you set the value of a parent class variable in an inherited class but then use it in an inherited function?

I have the following. Currently it doesn’t output anything for “$this->aa”. I want to be able to inherit the class, set some variables, then call the parent class functions to act on it. Am I going about this the wrong way?

class A {
    private $aa;

    function __construct() {
       $this->aa = "class a";
    }

    function parentmethod() {
       echo '['.$this->aa.']';
    }
}

class B extends A {
    function __construct() {
        $this->aa = "class b";
    }

}

$test = new B();
$test->parentmethod();

Advertisement

Answer

The problem here is the visibility of $aa. https://www.php.net/manual/en/language.oop5.visibility.php

private $aa make $aa only visible for class A

When you try to access $aa in B, you are dynamically creating a new property to B.

For the property to be visible by child, you need to change the visibility to “protected” in A.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement