|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2020-11-26 12:33 UTC] cmb@php.net
-Status: Open
+Status: Not a bug
-Assigned To:
+Assigned To: cmb
[2020-11-26 12:33 UTC] cmb@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 03:00:01 2025 UTC |
Description: ------------ While I am using the Public, Private, and Protected access modifier I found an error which is : Error is between Private and Protected modifiers By default, the scope of the Private variable should be within the class and not accessible to derived or child class. And The scope of the Protected variable should be within the class and its derived class. BUT It's acting vice-versa The private variable is accessible through the derived class which is wrong and the protected variable is not accessible through the derived class. Please check and revert back with a solution. PFB the code snippet for reference: // parent class class Vehicle { // protected property name protected $name; // public function start public function start() { echo $this->name. " - Engine start...<br/>"; } // public function stop public function stop() { echo $this->name. " - Engine stop...<br/>"; } } // child class class Car extends Vehicle { public function drive() { // accessing name variable of Car class echo "I am " . $this->name . "<br/>"; echo "Lets go on a drive..."; } } $car = new Car(); $car->name = "Mercedes benz"; // calling parent class method $car->start(); // calling child class method $car->drive(); Test script: --------------- // parent class class Vehicle { // private property name private $name; // public function start public function start() { echo $this->name. " - Engine start...<br/>"; } // public function stop public function stop() { echo $this->name. " - Engine stop...<br/>"; } } // child class class Car extends Vehicle { public function drive() { // accessing name variable of Car class echo "I am " . $this->name . "<br/>"; echo "Lets go on a drive..."; } } $car = new Car(); $car->name = "Mercedes benz"; // calling parent class method $car->start(); // calling child class method $car->drive(); Expected result: ---------------- If I used the protected keyword it should result in the following output: - Engine start... I am Mercedes benz Lets go on a drive... Actual result: -------------- While using the protected keyword it throws below error: Fatal error: Uncaught Error: Cannot access protected property Car::$name in C:\xampp\htdocs\PHP Programming\PHP OOPS\problem4.php:37 Stack trace: #0 {main} thrown in C:\xampp\htdocs\PHP Programming\PHP OOPS\problem4.php on line 37