Differences between public, protected, and private and the use of __set () and __get ()

Source: Internet
Author: User

The difference between public, protected, and private

Public represents the global, and the inner and outer subclasses of the class can be accessed;

Protected is protected and is accessible only in this class or subclass or in the parent class;

Private means that only this class can be used internally;

Among them, public has global and inheritance; protected is inherited; private can only be used by this class, not global and inherited.

Usage of __set () and __get ()

If an external program wants to get a private property inside the class, such as a private $name, you can define a __get ($a) method in the class to manipulate the $name value and return it, and the external object can then get a processed private $name value through $test->name.

If an external program wants to operate on a private property inside a class, you can define a __set ($a, $b) method in the class to manipulate the private property, and the external object is then able to manipulate the $name property by $test->name= "value".

For example:


Class test{
Private $name = "";

function __construct () {
$this->name= "Alice";
$this->age=20;
}


}
function __set ($a, $b) {
$this $a = $b;

}
$test =new test ();
echo $test->name. " <br> ". $test->age." <br> ";
$test->name= "ABCD";
Echo $test->name;
?>


The output is:

Alice

20

Abcd

Differences between public, protected, and private, and the use of __set () and __get ()

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.