What is the use of the __get () and __set functions in PHP classes?

Source: Internet
Author: User

When you try to get an unreachable variable, the class automatically calls __get.

Similarly, when you try to set an unreachable variable, the class automatically calls __set. In the Web site, these two are not functions that are not intended to be used. For example: Class Test { private $a = 1; private $b = 2; Public $c = 3;   Public function __get ($vname)     { return "You can not get";     }   Public function __set ($vname, $value)     { echo "You can not set";     } }   $t = new Test; Echo $t->a;//here trying to print out a private variable $t->b=3;//Here is trying to set the private variable If you want to operate directly on a private variable, you can't do it, of course. so at the time of reading, call __get (), output "You can not get"; at the time of setting, call __set (), output "You can not set". By the way, the __get () and __set () functions are set to public, otherwise they will be warning. The parameters of the __get () and __set () functions are 1 and 2, respectively, and cannot be omitted, regardless of whether the function is useless. By modifying the statements inside the __get () and __set () functions, you can implement a private variable that calls the class externally. For example: private __get ($vname) { return $this $vname; }If the value of $vname is a, then the correct value is returned. __set () is also the same.

Public Function __set ($vname, $value)
{
$this $vname = $value;
}

What is the use of the __get () and __set functions in PHP classes?

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.