Php 正在继承私有属性
理论上我知道私人成员不是继承的。但是我的代码给我的东西真的很让人困惑。 详情如下:Php 正在继承私有属性,php,inheritance,Php,Inheritance,理论上我知道私人成员不是继承的。但是我的代码给我的东西真的很让人困惑。 详情如下: class A{ private $ name; private $age; private $weight; private $height; function __construct ($Name, $Age, $Weight, $Height) { $this->name = $Name; $this->age = $Age; $this->weight = $Weigh
class A{
private $ name;
private $age;
private $weight;
private $height;
function __construct ($Name, $Age, $Weight, $Height)
{
$this->name = $Name;
$this->age = $Age;
$this->weight = $Weight;
$this->height = $Height;
}
}
// another class that extends A
class B extends A {
private $gender;
private $profession;
function __construct ($Gender, $Profession)
{
$this->gender = $Gender;
$this->profession = $Profession;
}
}
$aB = new B ("Male", "Teacher");
var_dump ($aB);
代码输出B属性的值,这是预期的,但它也尝试获取A属性的值,并打印A所有属性的值null。简而言之,它输出总共6个变量(属性)的名称和值。如果私有属性没有继承,为什么它包含类A的属性和值 B类无法访问私有属性 但是var_dump可以访问它是因为它是一个内部函数,并且它具有查看整个对象的“能力”。但是,您的代码没有这种能力
object(B)#1(6){[“性别”:“B”:private]=>string(4)“男性”[“职业”:“B”:private]=>string(7)“教师”[“姓名”:“A”:private]=>NULL[“年龄”:“A”:private]=>NULL[“体重”:“A”:private]=>NULL[“身高”:“A”:private]=>NULL}
谢谢!!这就是为什么下面这行代码在B中失败的原因:echo“$this->name”;对如果您想要继承属性,只需将“private”更改为“protected”