Public: The public attribute or method can be called in the subclass through self: var or self: method. you can call the method in the parent class through parent: method, however, the public owner cannot be called.
Public: public property or method
You can use self: var or self: method in a subclass to call methods in the parent class, but not public attributes.
You can use $ obj-> var or self: method to call an instance.
Protected: protected type
You can use self: var or self: method in the subclass to call methods in the parent class. you can use parent: method to call methods in the parent class.
You cannot use $ obj-> var to call a protected method or attribute in an instance.
Private: private type
Attributes or methods of this type can only be used in this class. Private attributes and methods cannot be called in instances of this class, subclass, and subclass.
Difference between self and parent
A) these two objects are often used in subclasses. Their main difference is that self can call public or protected attributes in the parent class, but parent cannot call
B). self: it indicates that the static member (method and attribute) of the current class is different from $ this, and $ this indicates the current object.
The instance code is as follows:
-
- Class BaseClass {
- Public $ public = 'public ';
- Private $ private = 'private ';
- Protected $ protected = 'protected ';
- Function _ construct (){
- }
- Function print_var (){
- Print $ this-> public; echo' ';
- Print $ this-> private; echo' ';
- Print $ this-> protected; echo' ';
- }
- }
-
- Class Subclass extends BaseClass {
- // Public $ public = 'public2 ';
- Protected $ protected = 'protected2 ';
- Function _ construct (){
- Echo $ this-> protected; // accessible, because the class is defined as protected, so this class or subclass can be used, and the value can be paid repeatedly in the subclass.
- Echo' ';
- Echo $ this-> private; // error because it is private, it can only be used in the baseclass class defined by her.
- }
- }
- $ Obj1 = new BaseClass ();
- $ Obj1-> print_var ();
- // Echo $ obj1-> protected; // error is protected and can be called only within the class or in the parent class of the subclass.
- // Echo $ obj1-> private; // The error is the same as the private one. it is called only in this class.
- Echo $ obj1-> public;
- Echo" ";
- $ Obj2 = new Subclass ();
- Echo' ';
- Echo $ obj2-> public; echo' ';
- Echo $ obj2-> protected;
- // Echo $ obj2-> private; // error
- // Echo $ obj2-> protected; // error
- ?>
Summary:
Public indicates global and can be accessed by external subclass inside the class;
Private indicates private, which can only be used inside the class;
Protected indicates that it is protected and can be accessed only in this class or subclass or parent class;