Setter and getter

Nov 11, 2020 By Puneet verma

What is Setter?

  • It is Used to control the changes to a variable
  • To set the variable value 
  • Also, knows as a Mutator 

What is Getter?

  • It is used to return the value
  • Used to get the value of the variable 
  • Also known as Accessor

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

  • Add validation to input. 
  • Add a character in front of roll no.
  • Display name in a small case.

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?

  • Maintainability 
  • Readability
  • encapsulation: variables are private, while Setter, Getter methods are public 
  • Hiding the internal representation of the property(variable) while exposing a property using an alternative representation(by methods).

Note: The variable should be declared as private