My question is more about terminology then technicalities (or is it?).
What’s the difference between a getter method and a public method in a class? Are they one in the same or is there a distinction between them?
I ask because I’m trying to learn best coding practices and this area seems grey to me. I was commenting my code out and noticed I had a big section called “Getters” and another big section called “Public Methods” and then I was like… “what’s the diff?!”.
Thanks!
In simple terms, a getter in PHP is simply a method that allows other parts of your code to access a certain class property.
For example:
A method may not necessarily be designed to just return a property though; you can create other methods so that your class can do funky things.
To expand on the above example, let’s give the
Personclass a method calledsay(), and give it a function/method parameter representing what to say:And call it after we create an object out of the class:
Notice that inside the
say()method I refer to$this->name. It’s OK, since the$nameproperty is found in the same class. The purpose of a getter (and its corresponding setter if any) is to allow other parts of your code to access this property.