Analysis on php object-oriented publicprivateprotected access modifier
Source: Internet
Author: User
This article provides a detailed analysis of the php object-oriented publicprivateprotected access modifier. For more information, see
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 The 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.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service