0

Why private properties are accessible from child class objects in PHP. according to the OOP concept, the private method can not be accessible from the child class but it seems that PHP is not following the OOP rule or anything else, please give a valid reason for this.

<?php
    class Car{
      private $model;
      public $noOfseats;
      public function setModel($m){
        $this->model = $m;
      }
    
      public function setNoOfSeats($n){
        $this->noOfseats = $n;
      }
      
      public function getNoOfSeats(){
        return $this->noOfseats;
      }
    
      public function getModel(){
        return $this->model;
      }
    
    }
    
    class SportsCar extends Car{
      private $style = 'fast and furious';
    
      public function driveItWithStyle(){
        return 'Drive a car with style '.$this->style;
      }
    }
    
    $sportsCar = new SportsCar();
    $sportsCar->model = "AXBCY";
    echo $sportsCar->model;
    
    ?>

1 Answers1

3

private means it's not inherited on child classes.

So this assignment creates a new public property in your child classes´ object:

$sportsCar->model = "AXBCY";

Whereas the parent classes´ private $model remains undefined.

mario
  • 144,265
  • 20
  • 237
  • 291