A built-in interceptor is available in PHP to intercept calls to undefined methods and properties. This article mainly introduces the PHP interceptor, in case form analysis of the common types of interceptor usage, very practical value, the need for friends can refer to,
specific as follows:
PHP provides several interceptors that are called when accessing undefined methods and properties, as follows:
1, __get ($property)
Functionality: Access to undefined properties is called
2, __set ($property, $value)
Function: Called when setting a value to an undefined property
3, __isset ($property)
function: Called when isset () is called on undefined property
4, __unset ($property)
function: Called when unset () is called on undefined property
5, __call ($method, $arg _array)
function: Called when undefined method is called
Here's a small program to illustrate the purpose of these interceptors:
Class intercept_demo{Private $xingming = ""; Private $age = 10; If an undefined property is accessed, the method function __get ($property) {$method = "get{$property}" that corresponds to get{$property} is called; if (Method_exists ($this, $method)) {return $this, $method (); }}//If a value is set for an undefined property, the method function __set ($property, $value) corresponding to the set{$property} will be called {$method = "set{$property}" ; if (Method_exists ($this, $method)) {return $this, $method ($value); }}//If the user calls the Isset method on an undefined property, function __isset ($property) {$method = "isset{$property}"; if (Method_exists ($this, $method)) {return $this, $method (); }}//If the user calls the Unset method on an undefined property,//is considered to be calling the corresponding unset{$property} method function __unset ($property) {$method = "un set{$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 property Name is Li"; $intercept->name = "Li"; echo "\ $intercept->name={$ Intercept->name} "; echo" Isset (name) ={$intercept->testisset ()} "; echo" "; echo" empties the property Name value "; unset ($intercept- >name), echo "\ $intercept->name={$intercept->name}", echo "", echo "Call undefined getage function"; echo "age={$intercept- >getage ()} ";