Advantages of Setters and Getters in OOP in PHP
In the previous lesson, we created a getter and setter for each property. One might ask, why are such complexities needed, because in fact the same effect can be achieved by making properties public, not private.
The point is that getters and setters have an advantage: before accessing a property, some checks can be performed. For example, in our case, when writing the name and surname, we can check that the new value is not an empty string:
<?php
class User {
private $name;
private $surn;
public function setName($name) {
if (strlen($name) > 0) {
$this->name = $name;
} else {
echo 'name is incorrect';
}
}
public function setSurn($surn) {
if (strlen($surn) > 0) {
$this->surn = $surn;
} else {
echo 'surn is incorrect';
}
}
public function getName() {
return $this->name;
}
public function getSurn() {
return $this->surn;
}
}
?>
Let's check how it works. First, let's create an object of the class:
<?php
$user = new User();
?>
Now let's try to write a correct value:
<?php
$user->setName('john');
?>
And now let's try to write an incorrect one:
<?php
$user->setName(''); // error
?>
In the Employee
class, in the age setter,
add a check that the age must be
from 0
to 120
.
In the Employee
class, in the salary getter,
make it so that when reading the salary,
a dollar sign is added to the end of its value.