
Jacob C. answered 09/30/19
Senior PHP Developer with Laravel, CodeIgniter, Wordpress experience
The concepts of public, private, and protected carry across all OOP languages, including PHP.
The idea is that the data inside a class should be hidden and not accessible from outside the class unless it absolutely has to be. So, these keywords do just that.
public - This is for data and methods that should be accessible outside the class. Think of this as your "public API" -- the functions that your class exposes so that people can use your class / library.
private - This is for "internal" data and functions. Things that no one needs to know about. Anything labeled private is inaccessible outside of the class. Attempting to access a private variable or method will result in an error.
protected - This is like "private", in that the data is inaccessible outside of the class -- *except* for subclasses. Any subclass that extends the class has access to these "protected" data and functions.
For example, if I have a class Dad:
A dad can `buySomething` but we don't want to give access to the underlying bank_account object -- we only need to allow access to the buySomething method to instances of Dad. Here, $john buys something that costs $1.00:
A child class, Son, may need access to $moms_phone_number in order to give her a call, so we make that variable protected in Dad class so that the Son, $jimmy, has access to it:
I hope this helps.
The official documentation on this: https://www.php.net/manual/en/language.oop5.visibility.php