Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在继承的类中设置父类变量的值,然后在继承的函数中使用它?_Php_Inheritance - Fatal编程技术网

Php 如何在继承的类中设置父类变量的值,然后在继承的函数中使用它?

Php 如何在继承的类中设置父类变量的值,然后在继承的函数中使用它?,php,inheritance,Php,Inheritance,我有以下几点。目前它没有为“$this->aa”输出任何内容。 我希望能够继承这个类,设置一些变量,然后调用父类函数来处理它。我走错方向了吗 class A { private $aa; function __construct() { $this->aa = "class a"; } function parentmethod() { echo '['.$this->aa.']'; } }

我有以下几点。目前它没有为“$this->aa”输出任何内容。 我希望能够继承这个类,设置一些变量,然后调用父类函数来处理它。我走错方向了吗

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

这里的问题是
$aa
的可见性

private$aa
make
$aa
仅对类
A

当您尝试访问B中的$aa时,您正在为B动态创建一个新属性

要使子属性可见,您需要在A中将可见性更改为“protected”