Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.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 - Fatal编程技术网

Php 为什么派生类访问基类私有属性?

Php 为什么派生类访问基类私有属性?,php,Php,我不明白这个话题。为什么基类的私有成员由派生类访问 <?php class A{ private $name; // private variable private $age; //private variable } class B extends A{ public function Display($name,$age){ echo $this->name=$name." age is ".$this->age=$age; } } $ob=new B();

我不明白这个话题。为什么基类的私有成员由派生类访问

<?php
class A{
private  $name; // private variable
private $age; //private variable
}
class B extends A{
 public function Display($name,$age){
 echo $this->name=$name." age is ".$this->age=$age;
   }
}

$ob=new B();
$ob->Display("xyz",23);
?>

输出:
xyz age是23

B
不继承
$name
$age
属性,因为它们是私有的

但是,PHP允许您分配变量,而无需首先将其声明为类属性:

<?php
class A
{
    private $name; // private variable
    private $age; //private variable

    public function __construct()
    {
        $this->name = "a";
    }
}
class B extends A
{
    public function display($name, $age) {
        $this->name2 = $name; // new name2 variable, NOT A's name
        $this->age2 = $age; // new age2 variable, NOT A's age
        echo $this->name2." age is ".$this->age2.PHP_EOL; 
        echo $this->name; // A's name, undefined property warning!
    }
}

$ob=new B();
$ob->display("xyz", 23);

您只需将变量设置为
受保护
而不是
私有