14
I’ve been noticing that most other libraries use the methods setters and getters (hereinafter referred to as mutator and accessor), to change the property of some classes.
For example:
class User
{
protected $name;
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
}
This is a classic example. I have a class that represents the user, and it has a property called name
, representing the user name. To change the value of name
, we need to use User::setName
, and to get it, User::getName
.
On the one hand we can think that it would be simpler to do something like:
$user = new User;
$user->name = 'Wallace';
I agree that this way would be the simplest. But there are cases where I recognize that it is necessary to create a way to validate how this name can be inserted or variable type.
Example:
public function setName($name)
{
if (is_string($name) && count(explode(' ', $name)) >= 2))
{
$this->name = $name;
return $this;
}
throw new InvalidArgumentException('Name is not valid');
}
Looking that way (and always only looking that way), I realize it’s useful to use mutators on account of being able to validate the data to be defined in a given object (such as type validation, or specific validations for an attribute).
Another detail is that if you are programming for interfaces, the same in PHP does not accept the definition of mandatory properties in an object, but only methods and constants.
But some questions that always come to mind is like a friend of mine who said: "PHP is not Java, it is not necessary to do such things".
So here are some questions about that:
I have also heard rumours that filling a class of methods can reduce performance.
Another detail is also that I see implementations of mutator/acessor with the use of magical methods __isset
, __get
and __set
, or __call
and __callStatic
. Some say there is also a question of performance reduction when using them.
So:
When I should wear it or not mutator/accessor in a class? Is this form used to standardize the code, or for an implementation, or is it just to imitate Java? (the last comment I’ve actually heard)
Is there any case (real) that I don’t need to use (for example, please, because I can’t see, because of what I mentioned about validations or possible future validations)?
Why libraries written in PHP (and "people") like to use more mutator/accessor than defining a public property for a class and defining it "externally"?
What do you think of those? http://answall.com/q/44739/101, http://answall.com/q/43757/101, http://answall.com/q/25995/101, http://answall.com/q/33723/101,
– Maniero
Thank you Mr @bigown. I now realize that most people don’t call it "mutator/accessor". You can close ;)
– Wallace Maxters
Or rather, it doesn’t close yet. This one has quotes about performance, maybe someone has something to say.
– Wallace Maxters