The Problem of Private Properties in Inheritance in OOP in PHP
The fact that private properties are not inherited can lead to an unexpected problem. Let's look at an example. Suppose we have the following parent class with a private property:
<?php
class User {
private $age;
public function setAge($age) {
$this->age = $age;
}
public function getAge() {
return $this->age;
}
}
?>
Suppose in the child class we decided to make a method that will increase the age by one. However, an attempt to change the private property of the parent will result in an error:
<?php
class Student extends User {
public function incAge() {
$this->age++; // error
}
}
?>
The error will disappear if in the child class
we declare a private property $age
:
<?php
class Student extends User {
private $age;
public function incAge() {
$this->age++;
}
}
?>
This is where the trap awaits us! In fact, we have created two private properties: one in the parent and one in the child. And they work completely independently. This means that the parent's methods will change their property, and the child's methods - theirs.
This problem actually has a solution. You just need to manipulate the private properties of the parent through the methods of that parent. Let's rewrite our code accordingly:
<?php
class Student extends User {
public function incAge() {
$age = $this->getAge();
$age++;
$this->setAge($age);
}
}
?>
Can be simplified:
<?php
class Student extends User {
public function incAge() {
$this->setAge($this->getAge() + 1);
}
}
?>
In the following code, the parent's method is overridden in the child class. Fix the problems in this code:
<?php
class User {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Employee extends User {
public function setName($name) {
if (strlen($name) > 0) {
$this->name = $name; // error
}
}
}
?>