PHP has three access modifiers:
Public (public, default)
Protected (protected)
Private)
Public (public, default) in PHP5, if the class does not have an access modifier for the specified member, the default access permission is public.
Protected (protected) is declared as a member of protected and can only be accessed by subclass of this class.
Private (private) is defined as a private member. it is visible to all Members in the class and has no access restrictions. Access to the outside of the class is not allowed.
Illustration
Demo
Copy codeThe Code is as follows: class Woman {
Public $ name = "gaojin ";
Protected $ age = "22 ";
Private $ height = "170 ";
Function info (){
Echo $ this-> name;
}
Private function say (){
Echo "this is a private method ";
}
}
// $ W = new Woman ();
// Echo $ w-> info ();
// Echo $ w-> name; // public attributes can be accessed
// Echo $ w-> age; // The protected attribute reports a fatal error.
// Echo $ w-> height; // The protected property reports a fatal error.
// Private method, Access Error
// $ W-> say (); // Private method, Access Error
Class Girl extends Woman {
// The public and protected methods of the parent class can be redefined, but private
// Protected $ name = "jingao"; // you can define a new one.
Function info (){
Echo $ this-> name;
Echo $ this-> age;
Echo $ this-> height;
}
Function say (){
// Parent: say (); // Private methods cannot be inherited. If the say method of the parent class is protected, no error is reported.
Echo "I am a girl ";
}
}
$ G = new Girl ();
$ G-> say (); // normal output
// Echo $ g-> height; // The private property cannot be accessed and no output result is returned.
// $ G-> info (); // This is the output gaojin22 $ height is private and the property is not inherited
// $ G-> height = "12"; // here, the height attribute is redefined and assigned a value.
// $ G-> info (); // The output is gaojin2212.