Is it really necessary to use mutator and access (Setter and getter) methods in PHP? What about performance?

Asked

Viewed 625 times

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"?

  • 2

    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,

  • Thank you Mr @bigown. I now realize that most people don’t call it "mutator/accessor". You can close ;)

  • Or rather, it doesn’t close yet. This one has quotes about performance, maybe someone has something to say.

2 answers

11

Getters and Setters were not created in Java, but were popularized by it, so their mandatory use is part of the hyper-abstraction culture of language where you can never write something that just works, it has to have multiple levels of abstraction, various methods that do nothing but inflate the amount of lines of code so you can feel that you are programming like a rock star while furiously typing those 10 getters and setters, what your IDE generates automatically but you like to do at hand to leave stunned passers-by with your coding skills .

Jokers aside the reason for the use you already know, you create access methods for the property so that if you want to do some processing before recovering them (getter) and before storing them (Setter), this is definitely very useful...when it makes sense. What happens in practice is you see several classes with dozens of getters/setters that do nothing and never will do, after all you may never need to process the attribute when recovering or setar or even this can be quietly done in the constructor, so in the end this is a pattern that most use without thinking or contesting, not necessarily bad.

How much the performance there is an overhead after all you exchange the direct access of the attribute by the call of a method that makes the access, even worse in the case of Magic methods since you end up dealing with the attributes by reflection. But you will have to work hard for this to have a palpable negative effect on your application, in the overwhelming majority of cases you should be more concerned with other things like cachear access to the bank rather than looking at micro-gettter/Setter optimizations versus direct access to attribute.

In the end I can only say that use is a personal matter, you can have a long happy life as dev (dev+feliz=runtimeerror) without ever using a getter/Setter, but there are always cases where using them would make your life easier.

  • 8

    +1 by "a pattern that most use without thinking or contesting".

10


The main reason to use methods getter and Setter is to have something other than simple access and attribution to the property.

So if you don’t have a processing, shouldn’t you use it? That’s not it, it might be interesting to use yes, and that answers the last question. It’s the old abstraction response. When you do this you’re guaranteed to be able to switch the access/assignment implementation whenever you want. You can put or take processing, after all the access will always be done by the method. If you leave direct access to the variable, you cannot change this without affecting the code that consumes the property.

After all there is no problem in computing that cannot be solved with an extra level of indirect. (What is indirect?)

It is also interesting for the aforementioned case of the interface. Incidentally this is the reason of existence interface, abstract the implementation.

So it’s not just to imitate Java, it will imitate Java code, but you may not use any of this if you prefer to write normal PHP code.

Need to use? No need, it can facilitate future maintenance. If you have a case where it’s right that the implementation can’t be changed, you never need to use.

There is certainly a higher cost in calling a method, but you already know, in PHP the difference is small. You have to measure to see if it is disturbing.

I advise reading Getters and Setters Methods and all the links constants there before you start using that resource.

  • The only case where I saw a framework leaving a property as public was on the Laravel, which is a property that receives true or false. There it makes sense not to have to use method (although some would make a point of creating a Setter for Boolean) :D

  • I don’t know. It depends. It might be Gambi. I have no way of knowing. Just asking for who did it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.