People keep telling me I should be using public, private, or protected access modifiers in front of all of my class properties and methods. I really don’t understand why. I’m new so bear with me, but the way I see it is this:
-
I am the only one who will work on my code. Not a team.
-
I already know what everything means, plus using an editor that tells me all the declared vars and properties, I know I’m not going to step on my used variables.
One of the explanations I get is that it “protects or hides” your code from people who could see it…..but in PHP there’s no way that I know of for a user to see your code in the first place, who am I hiding it from? If they CAN see my code then they are either a hacker or they are in my account so I can’t stop them anyway.
I can understand if I were working with huge code on a team, but for small things it seems unnecessary.
You’re not “hiding” your code from anybody, that’s nonsense.
What
protectedandprivateproperties are doing is to tell PHP how you intend to use them. When you create a class, you should usually have an idea of how you want that class to be used. You will havepublicparts, which other code can interact with, and other parts that you do not want to have other code access directly. Typically you want to restrict thepublicparts of a class to a very small set of well defined methods which are not going to change. Because once you are using them in other parts of your code, changing them becomes a pain. All theprivateandprotectedstuff should only be accessed within the class itself, so changing it around is less of a problem later.If you’re the only one working on the code you may say it’s as easy as simply not using the “private parts”. But you are going to make mistakes, and you are going to forget what part belongs where over time. Marking these properties explicitly as
protectedorprivatelets PHP help you not violate your own “terms of use”. It’s the difference between a mental note of “don’t touch this” and actually putting a lock on something.