When should scopes be used?
public static protected private

  • Can someone explain in what situations to use it? Preferably with examples and explanations - Mr. Black

3 answers 3

Scopes help you determine what is gibblered and what is not. The public scope says to everyone else: look, I provide this functionality here:

 class RepositoryFactory { public function getRepository(string clazz) { ... } } 

All methods that belong to the project internals should be private or protected - this is not protection from the hawks; it is a way to hide the unnecessary from those who use your class.

 class RepositoryFactory { private function checkClassExistence(string clazz) { ... } } 

In this case, this method is unlikely to be of interest to the outside world, it is only needed to help public methods, so it is hidden.

The only difference between protected and private is that protected can be redefined in a descendant class, so the same RepositoryFactory can perform some of its internal checks before taking any actions - and these checks can be extended or narrowed -Head To provide this opportunity to successors, the method is declared as protected:

 class RepositoryFactory { protected function isValidRepositoryClazz(string clazz) { ... } } 

Typically, such functionality is required in very rare cases, and almost all of the internal trading is taken out in private .

The static modifier is not a scope modifier and controls the context in which a field or method exists. In the usual case, we operate in the context of a specific instance of a class; if static is used, we operate in the context of the class itself; thus, static methods do not have this and can be called from any part of the program, and static variables exist only in a single instance in the whole program (as opposed to instance fields bound to a particular instance).

  • one
    @Doofy: From you, of course. Today you remember what and how you can change, and forget it in a year. - VladD
  • one
    @Doofy: Good for you! And I still can not remember in the old projects, what's what. But with private immediately clear: it is not allowed - it is impossible to touch, the compiler will not allow. (And if there are a lot of people in the project ...) - VladD
  • one
    It will still be forgotten, and very fast. The general essence is clear, but the details of the implementation for a long time in my head are not delayed. In addition, it is simply comfortable and logical. And not only for myself, but also for any other developers who will work with the code. It’s one thing to have a wrapper on available class methods, some of which should not be accessible from the outside just like that, it’s another thing to have a few talking methods without details of their implementation. - DanielOlivo
  • one
    @Doofy, not only. I will try to give an example in words. You have several int fields in your class, for example, and the logic of your class includes the fact that these fields must be in the range [1; 5] for example. If these fields were public, then from the external code it would be possible to install at least in 999 and everything, the logic of the class’s work violates it. And so you make them private, and the public method setter, which does not allow you to set values ​​out of range. Everyone is happy. Just one example, but you can come up with hundreds of this. - DanielOlivo pm
  • one
    @Doofy on who will use this class. All that is private / protected is internal methods that do not return the final result, and therefore uninteresting to the outside world. So that they do not interfere with the feet and do not fall out in the IDE autocomplex, they are easier to hide. - etki pm

My answer is a small addition to others. This is just an attempt to associate with objects in the real world, on the basis of which the PLO was conceived. Please consider the narration in view of this position.


There are many different formal explanations for why one should restrict oneself to access to certain members and methods of the class, but questions about this need with enviable regularity emerge one after another. Then, perhaps, in explaining the essence should go a different way.

If the subject of discussion is a certain object, then why not submit to it a prototype that exists in the real world. Let it be a car.

"Public" scope

Imagine that the factory suddenly decided to make absolutely all parts of the machine available to the driver without having to go far into the bowels of the mechanism. Engine pounded? Only stretch out your hand, tighten some sticking bolt in sight, everything is all right. Is the oil over? Ley right in the cabin in any tube peeping out of the glove compartment. Did the muffler fall off? Why crawl under the car and weld something, when you can simply attach the hose to the outlet pipe at one end, and put the other end in the window. All the bolts, all the nuts, springs and other parts, all of this sticks out, gleaming merrily at the sun or frowning with the driver on a bad weather day.

It is terrible to even imagine what kind of monster in the end it would turn out if this fantasy turned out to be real. It is reasonable to assume that such an aggregate would not even budge. And all because in all the variety of parts available to control and tune, only a small fraction relates directly to traffic control, which the driver performs. Roughly speaking, the steering wheel, pedals and forward, and whether there is a charge in the battery or not, the driver should be disturbed only if the car does not start.

Scope "private"

The driver, as a user of the mechanism, should not care what internal processes take place in one or another part of the latter. The driver is focused on driving, on not accidentally distracting, and at the same time not introducing himself in case of loss of control over the situation.

However, the situation changes when it is time for maintenance. The driver arrives at the auto repair shop and a team of professional technicians takes over his car. Of course, if the car has gone through fire, water, and even copper pipes, then in this situation, the technicians may not take up the job and cheerfully offer to consider the issue on the subject to the nearest landfill. Well, or to the factory, which is the genius of a mechanical miracle.

Scope of "protected"

However, part of the work on the restoration and even modernization of the car, savvy masters can perform. For example, hang deodorant on the windshield in the cabin. This little specialty detail will significantly change the mood of the driver for the better, because it will make driving more convenient and comfortable. Also, special changes may be made to the hands of the driver himself, if, in the opinion of the technicians, they do not grow from the place that is needed in the implementation of safe traffic.

Keyword "static"

One day, having replayed computer games, a young driver may suddenly decide that he is a grand thief auto and start getting into other people's cars, as if they were him. In this case, the offender will not be interested in the fact that the documents are issued for completely different people. He just uses cars when he wants. And if in real life such behavior can lead to serious consequences, in the world of the code this is quite acceptable by the creator. And when and how to limit the behavior of the experimental one, the creator usually decides without straining too much and for another cup of freshly ground coffee.

  • Very interesting metaphor. Only now with static I still do not understand - Mr. Black
  • @Doofy, imagine that static is a kind of communism. You can go outside and ride on any free car. You did not buy it at the car dealership, do not own it, but you can still ride it without breaking the law. - alexis031182 pm
  • @ alexis031182, can I clarify? I probably do not fully understand the insides of static. The presented analogy is that static is when each object has something completely common, and this is true, but it turns out that static is the level of the object anyway. Maybe I misunderstood the analogy, it is hard to understand. I believed that static is the context of the very essence of a class, which does not need any object at all, although they may be something at the meta level. In the analogy with cars, I can’t think of an example in which the existence of cars is not needed at all. - DanielOlivo pm
  • one
    @Doofy, yes, but it will even exist without variables with access through the class name. - DanielOlivo
  • one
    @Doofy needed. You wrote everything correctly, you just have the opportunity to access $ a through A :: $ a. - DanielOlivo 6:24 pm

In the same as in other languages. public for the object / class muzzle, that is, what is available to users and successors, protected if access is not needed from outside the objects / class, but it is necessary to have access in successors, private for everything else. static is a member at the class level, not an object, for example, any auxiliary methods, fields, whole classes whose objects are not required to be created, etc. In general, this is all in the initial literature on the EP is much better written.

  • I read about their designations and why they are, but I can not understand in what situations to use it. PHP for me right now is just like the server side and I can't imagine why you need to protect variables. Therefore, such answers " private for everything else " do not teach me anything :( - Mr. Black