Example Analysis of Interceptor in PHP
- 2021-07-24 10:23:53
- OfStack
This article illustrates the interceptor usage of PHP. Share it for your reference. The details are as follows:
PHP provides several interceptors to be called when accessing undefined methods and properties, as follows:
1, __get ($property)
Function: Access to undefined properties is called
2, __set ($property, $value)
Function: Called when setting a value for an undefined property
3, __isset ($property)
Function: Called when isset () is called on an undefined property
4, __unset ($property)
Function: Called when unset () is called on an undefined property
5, __call ($method, $arg_array)
Function: Called when calling an undefined method
The following will explain the purpose of these interceptors through a small program:
class intercept_demo{
private $xingming = "";
private $age = 10;
// If accessed 1 Is not defined, a call is made to the get{$property} Corresponding method
function __get($property){
$method = "get{$property}";
if (method_exists($this, $method)){
return $this->$method();
}
}
// If given 1 Undefined property setting values, the call is made to set{$property} Corresponding method
function __set($property, $value){
$method = "set{$property}";
if (method_exists($this, $method)){
return $this->$method($value);
}
}
// If the user calls an undefined property isset Method,
function __isset($property){
$method = "isset{$property}";
if (method_exists($this, $method)){
return $this->$method();
}
}
// If the user calls an undefined property unset Method,
// Is considered to call the corresponding unset{$property} Method
function __unset($property){
$method = "unset{$property}";
if (method_exists($this, $method)){
return $this->$method();
}
}
function __call($method, $arg_array){
if (substr($method,0,3)=="get"){
$property = substr($method,3);
$property = strtolower(substr($property,0,1)).substr($property,1);
return $this->$property;
}
}
function testIsset(){
return isset($this->Name);
}
function getName(){
return $this->xingming;
}
function setName($value){
$this->xingming = $value;
}
function issetName(){
return !is_null($this->xingming);
}
function unsetName(){
$this->xingming = NULL;
}
}
$intercept = new intercept_demo();
echo " Setting Properties Name For Li";
$intercept->Name = "Li";
echo "\$intercept->Name={$intercept->Name}";
echo "isset(Name)={$intercept->testIsset()}";
echo "";
echo " Empty attributes Name Value ";
unset($intercept->Name);
echo "\$intercept->Name={$intercept->Name}";
echo "";
echo " Invoke the undefined getAge Function ";
echo "age={$intercept->getAge()}";
I hope this article is helpful to everyone's PHP programming.