从理论上讲,我知道私人成员不是继承的。但是我的代码给了我的东西真的很混乱。 它如下:
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的属性和值。
答案 0 :(得分:2)
B类无法访问私有财产。
但var_dump可以访问它是因为它是一个内部函数,它具有" power"查看整个对象。但是,你的代码没有那种力量。
object(B)#1 (6) { ["gender":"B":private]=> string(4) "Male" ["profession":"B":private]=> string(7) "Teacher" ["name":"A":private]=> NULL ["age":"A":private]=> NULL ["weight":"A":private]=> NULL ["height":"A":private]=> NULL }