getter和setter如何在PHP中工作[重复]

This question already has an answer here:

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?

</div>

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!