Access control in PHP5! Public, private, protected

Source: Internet
Author: User
Access control in PHP5! Public, private, protected, read access control in PHP5! Variable definitions of classes in public, private, protected, and php5oop follow one type of access control: public indicates global, and internal and external subclasses of the class can be accessed; private indicates private, only this class can be used internally; protecte

The variable definition of classes in php5 oop follows an access control policy:

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;

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;
?>

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.