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?