Method Chaining in OOP in PHP
It is possible to make methods callable
one after another in a chain. For
this, each such method must
return $this. Let's
try it. Let's add the corresponding
code to the setters of our class:
<?php
class User {
private $name;
private $surn;
public function setName($name) {
$this->name = $name;
return $this;
}
public function setSurn($surn) {
$this->surn = $surn;
return $this;
}
public function getName() {
return $this->name;
}
public function getSurn() {
return $this->surn;
}
}
?>
Now our setters can be called one after another, in a chain. Let's test it. Let's create an object of our class:
<?php
$user = new User();
?>
Let's call our setters in a chain:
<?php
$user->setName('john')->setSurn('smit');
?>
Let's check that the property values have changed:
<?php
echo $user->getName();
echo $user->getSurn();
?>
Make it so that the setters
of the Employee class
can be called in a chain.