Just a simple question. I've seen many cases where the code is implemented like the following:
class User { private $id; private $firstname; private $lastname; public function __construct() { some code } public function getId() { return $this->id; } public function getFirstname() { return $this->firstname; } public function setFirstname($value) { $this->firstname = $value; } } // And properties are accessed like: $user->getFirstname(); $user->getId(); So what is the reason of using private properties and having public getters, instead of making the properties public and accessing them directly like:
$user->firstname; PS: Is it OK if I use the second method?
EDIT
Seems like I did not research well before asking this question (guess I used wrong keys to search on the topic). Here is another good answer to (almost) the same question: https://stackoverflow.com/a/1568230/1075534
Basically, for my case, one good reason to use getters and setters is to avoid changing 250 classes that directly access the property. So for example, imagine that I was not using a getter:
class User { public $firstname = 'abc'; public $lastname = 'cde'; } $user = new User(); echo $user->firstname . ' ' . $user->lastname; Now, imagine that I want to change the behavior of my app and I decide to print names as capitalized. In this case then I would search each implementation (250 in this case :) and capitalize the output wherever I called the properties. But, rather If I used a getter then I would just change the getter method:
class User { private $firstname = 'abc'; private $lastname = 'def'; public getFirstname() { return ucfirst(strtolower($this->firstname)); } public getLastname() { return ucfirst(strtolower($this->lastname)); } } Also, bear in mind that a getter might not only gather information from a single property. Imagine the following:
class User { private $firstname = 'abc'; private $lastname = 'def'; public function getName() { return $this->firstname . ' ' . $this->lastname; } } For those who still have questions on this matter, I suggest them reading the material that Gordon provided and especially the answer that I've linked.