Visibility
private hides a field; a method hands out the value.
public is visible from outside. private is visible only inside the class. protected is visible in the class and its subclasses. A field that anyone can overwrite holds no rule. The rule lives in a method.
A getter makes sense when the value is read from outside but not changed. A pile of setters without checks is just public fields. If a name is set once, keep it in the constructor and do not write a setter.
In PHP 8 a property can be declared right in the constructor: __construct(private int $n). That is both the declaration and the assignment. For a short box with a number it is even clearer. From outside, $box->n can no longer be read if it is private. It is read through a method.
Do not make every method public "just in case". A public method is a promise. A private one can be renamed tomorrow. The more is public, the more it hurts to change the class once someone else's code depends on it.
Practice
Who sees private
From where can a private field be read?
- From any file
- Only from this class
- Only from main
- From nowhere, not even from methods
The name in the task
What is the method that returns the hidden number called? One word.
A hidden number
Hide the number 7 in a private field and print what get returns.