class Person {
public $name;
private $age; //private access
}
class Employee extends Person{
public $id;
public $salary; //class property
}
$emp = new Employee();
$emp->name="ABCD";
$emp->age = 30;
$emp->id=101;
$emp->salary=20000;
echo "<br/> Name : ".$emp->name;
echo "<br/> Age : ".$emp->age;
In this code, the child class variable $emp
can access private member of parent class Person
directly. Is this not the violation of private access rule?
It gives error when using a parent class variable, but works with child class variable!! Can anyone explain why?
You need to define it as protected . Protected members are inherited to child classes but are not accessible from the outside world. after inheriting protected members, you can provide public access. then we should avoid to keep personal data in protected access specifier.
public, protected and private inheritance in C++ protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.
TLDR;
$emp->age = 30
does not call parent private member age
, it creates new child object property age
dynamically.
Explanation
Looks like a bug, doesn't it? Firstly, let's comment out the parent's private member:
<?php
class Person {
// private $age;
}
class Employee extends Person {
}
$emp = new Employee();
$emp->age = 10;
echo $emp->age . "\n";
//out: 10
In the line $emp->age = 10
we created new property of $emp
object named age
and assigned it value 10
.
When you define your parent's member as private, children don't see this member at all:
<?php
class Person {
private $age;
function __construct() {
$this->age = 30;
}
public function printAge()
{
echo sprintf("Parent::age = %s\n", $this->age);
}
}
class Employee extends Person {
private $age;
function __construct() {
parent::__construct();
$this->age = 10;
}
public function printAge()
{
echo sprintf("Employee::age = %s\n", $this->age);
parent::printAge();
}
}
$emp = new Employee();
$emp->printAge();
//out:
//Employee::age = 10
//Parent::age = 30
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With