Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I bother with getters and setters in PHP?

I am making a new class in PHP. I don't anticipate this class ever being extended. Should I bother with making class members private and implementing getter and setter functions?

Part of me thinks that this is just a big waste of time and only serves to bulk up my code.

The class is for a resume. I am writing it in code to demonstrate my coding style. The question is will an employer want to see getters and setters, or will that just clutter things up?

like image 417
james Avatar asked Dec 10 '10 20:12

james


2 Answers

I don't want once again to repeat the argument that even that you don't expect inheritance now, you may still need it in the future, but they are still more reasons to use getters and setters:

  • Getters and setters will let you easily implement validation of your properties
  • Your code will follow good coding guidelines and as such it will be easier to be read by others. If I ran into a code file that didn't use getters and setters, I would be very skeptical about it and would have to read it carefully many times.
  • Also this is not only a per class decision, but a decision for your whole project. Do you want to have getters and setters for some classes you need them and not for some others? I believe that consistency is important.
  • There are tools that can autogenerate writing the getters and setters for you. Remember that you write the code only once, but you read it many times,
like image 71
kgiannakakis Avatar answered Sep 22 '22 06:09

kgiannakakis


Check out the __get and __set magic methods, it'll keep your code clean and you won't have to feel lazy for not setting variable scopel.

public function __get($name)
{
  return $this->$name;
}

public function __set($name, $value)
{
  $this->$name = $value;
}

Obviously you'd have more detail, but that will handle your accessors.

like image 33
Parris Varney Avatar answered Sep 26 '22 06:09

Parris Varney