$ this->给出错误,但$ this-> a = 20; 输出为什么? [重复]

This question already has an answer here:

<?php
    class Test
    {
        private $a = 10;
        public $b ='abc';



}
class Test2 extends Test
{

    function __construct()
    {

         echo $this->a;
         echo $this->a = 20; // wh
    }

}
$test3 = new Test2();
</div>
echo $this->a;

echoes value of class property a. This property is not defined, because property a of class Test is private and therefore is not available in class Test2. So, property a is created in class Test2.

echo $this->a = 20; // wh

does the next: assigns 20 to a property (which was created on the previous line) and echoes result of assignment which is 20.

The solution:

class Test
{
        // protected property is avalilable in child classes
        protected $a = 10;
        public $b ='abc';
}

class Test2 extends Test
{
    function __construct()
    {
         echo $this->a;
         $this->a = 20;
         echo $this->a;
    }
}
$test3 = new Test2();  // outputs 10 20

You should change

private $a = 10;

to:

protected $a = 10;