R
R
Roman Sarvarov2020-04-17 11:09:14
PHP
Roman Sarvarov, 2020-04-17 11:09:14

Can you give an example of when to use private and when protected?

I can't fully understand the benefits of using the private access modifier instead of protected.
After all, one of the principles of SOLID says that in order to change something in a class, you do not need to change its code - you need to do it through inheritance. Is it possible to always use protected in this case?

Can you give an example of when it is better to use private for functions and class properties, and when it is better to use protected? It is possible in any language.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VicTHOR, 2020-04-17
@megakor

To change something in a class, you do not need to change its code - you need to apply the decorator pattern .
There is a design principle: “prefer composition to inheritance, as well as the principle: “design at the abstraction level.”
In general, if you can create an object of a class, you should not inherit from it, it’s better to delegate part of the functionality to such an object in the new class and add new functionality , something like this.
Of course, private is needed for cases where nothing should come out (except through a getter.
Protected is useful for the design principle at the abstraction level, when you can select the common (and make it protected) and separate the changing ( one more principle, by the way).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question