⊗ppOpIhPrM 31 of 107 menu

Private Methods in Inheritance in OOP in PHP

Private methods are not inherited. This is done intentionally to not violate encapsulation. Let's look at an example. Suppose we have the following parent class with a private method:

<?php class User { private $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->capeFirst($this->name); } private function capeFirst($str) { return ucfirst($str); } } ?>

Suppose the following class inherits from the parent class:

<?php class Student extends User { private $surn; public function setSurn($surn) { $this->surn = $surn; } public function getSurn() { return $this->surn; } } ?>

Suppose the descendant wants to use the parent's private method. PHP will not allow this and will throw an error:

<?php class Student extends User { private $surn; public function setSurn($surn) { $this->surn = $surn; } public function getSurn() { return $this->capeFirst($this->surn); // there will be an error } } ?>

Try to use the parent's private method in the Employee class.

byenru