I have come to realize that most other libraries use the setters and getters methods (hereafter referred to as mutator and accessor in>), to change the ownership of some class.
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
, which represents 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 would be the simplest way. But there are cases where I recognize that it is necessary to create a way to validate how this name can be entered or type the variable.
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 at this side (and I always look only on that side), I realize that it is useful to use mutators because it can validate the data that will be defined in a given object (such as type validation, or specific validations for an attribute).
Another detail is that if you are #
But some questions that always come to mind is like a friend of mine who said, "PHP is not Java, you do not have to do such things."
So here are some questions about this:
I've also heard some rumors that filling a class of methods can reduce performance .
Another detail is also that I see implementations of mutator / accessor using magical methods __isset
, __get
and __set
, or __call
and __callStatic
. Some say that there is also a question of performance reduction when we use them.
Thus:
-
When should I use 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 actually heard)
-
Why do libraries written in PHP (and "people") like to use mutator / accessor rather than defining a public property for a class and defining it "externally "?