⊗ppOpIhPrP 32 of 107 menu

Private Properties in Inheritance in OOP in PHP

Private properties are not inherited. But a descendant can manipulate them through the parent's public methods. Let's see it in practice. Suppose we have the following parent class with a private property and its getter and setter:

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

Let the following descendant inherit from this parent:

<?php class Student extends User { } ?>

Let's create an object of the descendant:

<?php $student = new Student; ?>

Let's use the parent's method to set its private property:

<?php $student->setName('john'); ?>

Let's use the parent's method to read its private property:

<?php $name = $student->getName(); echo $name; ?>

Given the following parent class:

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

Make a class Employee, which will inherit from this parent.

Create an object of the class Employee and call the inherited setters and getters.

In the class Employee, make the following method:

<?php public function getFull() { return $this->name . ' ' . $this->surn; } ?>

Make sure the method's code leads to an error.

byenru