Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private access in inheritance

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?

like image 811
Mangesh Kherdekar Avatar asked Nov 08 '17 10:11

Mangesh Kherdekar


People also ask

How do you make private members accessible in inheritance?

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.

What is public and private inheritance?

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.


1 Answers

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
like image 153
Ivan Kalita Avatar answered Oct 14 '22 07:10

Ivan Kalita