When and why should I use public
, private
, and protected
functions and variables inside a class? What is the difference between them?<
Reviving an old question, but I think a really good way to think of this is in terms of the API that you are defining.
public
- Everything marked public is part of the API that anyone using your class/interface/other will use and rely on.
protected
- Don't be fooled, this is also part of the API! People can subclass, extend your code and use anything marked protected.
private
- Private properties and methods can be changed as much as you like. No one else can use these. These are the only things you can change without making breaking changes.
Or in Semver terms:
Changes to anything public
or protected
should be considered MAJOR changes.
Anything new public
or protected
should be (at least) MINOR
Only new/changes to anything private
can be PATCH
So in terms of maintaining code, its good to be careful about what things you make public
or protected
because these are the things you are promising to your users.