user5648637
user5648637

Reputation: 33

private attributes getting inherited

Theoretically I know that private members are not inherited. But what my code gives me is really confusing. It is as follows:

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

The code outputs values for attributes of B, that is expected, but it also attempts to get values of attributes of A and prints the value null for all attributes of A. In short, it outputs name and value of total 6 variables (attributes). Why it is including the attributes and values of class A if private properties are not inherited.

Upvotes: 1

Views: 47

Answers (1)

Andrey
Andrey

Reputation: 441

Class B can't access to private properties.

But var_dump can access it is because it is an internal function, and it has the "power" to view the whole object. However, your code doesn't have that 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 }

Upvotes: 2

Related Questions