Public: methods or attributes can be accessed in any scope, and this is the default value. If an access modifier is not specified for an attribute or method, It will be public.
Protected: A method or attribute can only be accessed from a class or a member of an inherited class.
Private: methods or attributes can only be accessed from one member of the class, and cannot be accessed from members of the inherited class. Methods or attributes marked by private can be redefined in the inheritance class. Each class can only see its own private method.
The three modifiers should be sorted from large to small in terms of scope:
Public → protected → private is in the scope of action because some attributes and methods are encapsulated by PHP classes like our previous functions. This encapsulation determines the "visibility" of the data, so that we can only call the defined attributes and methods without modifying them outside the class. This is the benefit of encapsulation, it also improves security. To illustrate the functions of these modifiers, see the following code:
- <? Php
- Class myClass {
- Public $ public = "Public ";
- Protected $ protected = "Protected ";
- Private $ private = "Private ";
- Function say_Hello (){
- // I will not do anything now. I will tell you later
- }
- }
- $ Obj = new myClass ();
- Echo $ obj-> public;
- // Echo $ obj-> protected;
- // Echo $ obj-> private;
- ?>
- <? Php
- Class myClass {
- Public $ public = "Public ";
- Protected $ protected = "Protected ";
- Private $ private = "Private ";
- Function say_Hello (){
- // I will not do anything now. I will tell you later
- }
- }
- $ Obj = new myClass ();
- Echo $ obj-> public;
- // Echo $ obj-> protected;
- // Echo $ obj-> private;
- ?>
Run the above example to get a "Public", but when you remove the comments of // echo $ obj-> private;, you will get the following error: Fatal error: cannot access protected property myClass: $ protected in E: apachehtdocsexamplefile. php on line 13.
We can see that we cannot define the attributes of the runtime class at will, that is, we cannot modify some operations already defined in the PHP class encapsulation, Which Is visibility. We do not know the Members in this class in the "outside", because these Members may be invisible to other classes.
Of course, if we must access or modify the attribute defined as "private", we can also use the system methods provided by PHP: _ get () and _ set (). I will learn more about this in the future, because I only know about it now.