The examples in this article describe the various interceptor usages in the PHP class. Share to everyone for your reference. The specific usage analysis is as follows:
1, __get ($property) called when accessing an undefined property
Copy Code code as follows:
Class Lanjie
{
function __get ($name)
{
echo $name. "Not found! ";
}
}
$ob = new Lanjie ();
Echo $ob->g;
When we call the object $ob undefined property g, the Interceptor __get () method is invoked to output the "G" not found! ;
2, __set ($property, $value) assigning values to undefined property calls
Copy Code code as follows:
Class Person
{
Private $_age;
Private $_name;
function __set ($name, $value)
{
$method = "Set". Ucfirst ($name);
Echo $method;
if (Method_exists ($this, $method))
{
return $this-> $method ($value);
}
}
function SetName ($name)
{
$this->_name = $name;
if (!is_null ($this->_name))
{
$this->_name = strtoupper ($this->_name);
}
}
function Setage ($age)
{
return $this->_age = (int) $age;
}
}
$p = new Person ();
$p->name = ' Bob ';
Print_r (Array ($p));
Here we can see very clearly that when you assign a value to an undefined ' name ', you Invoke "__set ()"
Others are __call (), __isset (), __unset ();
The most useful and commonly used of these is __call (), which is invoked when an existing method is invoked, and __isset () is invoked when the Isset () function is used on a defined attribute, __unset is invoked when the unset is used on an undefined number
I hope this article will help you with your PHP program design.