What is Setter?
What is Getter?
How to use Setter and Getter?
Normal Way
class Example{
private $name;
private $roll;
public function start()
{
$this->name ='Puneet';
$this->roll = 24;
echo $this->name; // Puneet
echo $this->roll; // 24
}
}
Setter and Getter
class Example{
private $name;
private $roll;
public function start()
{
$this->setName('Puneet');
$this->setRoll(24);
$this->getName(); // Puneet
$this->getRoll(); // 24
}
public function setRoll($roll)
{
$this->roll = $roll;
}
public function setName($name)
{
$this->name = $name;
}
public function getRoll()
{
return $this->roll;
}
public function setName()
{
return $this->name;
}
}
Why we need Setter and Getter?
Practically speaking, we can write the whole application without even bother about Setter and Getter.
Client woke up you after 5000years and asked you to
We need to propagate all these changes in several places. It required 100years to reflect all these changes and another 100years to test all these changes.
I think after hearing all this, you will again sleep for 5000years.
Wait, there is a solution to this.
Instead of setting and using the variables every, make a single point to set and get the variables. i.e. Setter and Getter.
Why we need Setter and Getter?
Note: The variable should be declared as private