Useful if you want to apply OOP methods such as Encapsulation Information .
If you declare class members as private , they cannot be accessed from code outside your class. You must provide access methods to them. This separates the interface of your class from the actual implementation.
Another code that your class uses does not have to know the name of the class member or how you actually store the information inside.
Example:
Consider the Books class, somehow giving me a list of books. I can define a public member that contains an array of books:
class Books { public $list; }
On the other hand, if I define the getList() method, I can change the implementation later without executing the code that the class uses:
class Books { private $list; public function getList() {
Obviously, you do not need modifiers such as private , protected or public to implement this behavior, but this leads to improved structured code and clearer interfaces. Imagine you have a class that has both public $list and the getList() method. How do you know which one to use?
This is used not only to get values, but especially to set values.
There are no drawbacks if you use them, only the benefits of IMHO. The difference between them is scope. public elements can be accessed from external code; protected elements can be accessed by the class inheritance form and private only class members.
Methods can also have these modifiers and follow a similar goal. For instance. if the method is declared as private , then it is clear that this is probably some kind of helper method that is used only internally and should not be called external.
So in the end it comes down to two things:
- Control . Which parts of your class can be accessed, how
- Self-documenting or understanding . Other people using your class can more easily determine which part of your class they should access and which should not.
source share