0

I need to know how getter and setter will work in PHP. Because some interviewer asked tricky question about getter and setter. I have failed to explain. Can any one help me out?

1 Answers1

1

Getters and setters are used to- at a later stage- make it possible to provide logic when the developer requests or sets a variable.

If you, for example, want to add a layer of validation to prevent your object from being misused. What if you wanted to make sure that the person’s $name variable is a string variable and not something else? Well, we can simply add that layer of validation to our setter method:

//Set the person's name.
public function setName($name){
   if(!is_string($name)){
       throw new Exception('$name must be a string!');
   }
   $this->name = $name;
}

In the PHP code above, we modified the setter method setName so that it validates the $name variable. Now, if a programmer attempts to set the $name variable to an array or a boolean, our function will throw an Exception. If we wanted to, we could also make sure that the $name variable is not a blank string.

Big thanks to this post.

Best of luck on your interview!

Thoby
  • 316
  • 1
  • 6
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/15886257) – mickmackusa Apr 19 '17 at 12:33
  • @mickmackusa Absolutely true! Better like this? – Thoby Apr 19 '17 at 12:45
  • Much better. Thank you for your good SO citizenship. – mickmackusa Apr 19 '17 at 12:47