Analysis of Interceptor Usage in php Class
- 2021-07-24 10:23:57
- OfStack
This article illustrates the use of various interceptors in the php class. Share it for your reference. The specific usage analysis is as follows:
1. Called when __get ($property) accesses an undefined property
class lanjie
{
function __get($name)
{
echo $name." property not found! ";
}
}
$ob = new lanjie();
echo $ob->g;
When we call the undefined property g of the object $ob, we call the interceptor __get () method and output "g property not found!";
2. __set ($property, $value) assigns a value to an undefined property when it is called
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 clearly see that "__set ()" is called when assigning a value to an undefined 'name'
Others are __call (), __isset (), __unset ();
The most useful and commonly used here is __call (), which is called when a method is called; __isset () is called when using the isset () function for a defined attribute, and __unset is called when using unset for an undefined number
I hope this article is helpful to everyone's PHP programming.