Analysis on php object-oriented public private protected access modifier

Source: Internet
Author: User

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.

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.