This article mainly introduces the PHP interceptor and analyzes the common usage of various interceptors in the form of examples, which is of great practical value, you can refer to the following example to describe the PHP interceptor usage. Share it with you for your reference. The details are as follows:
PHP provides several interceptors for calling when accessing undefined methods and attributes, as shown below:
1. _ get ($ property)
Function: The undefined access property is called.
2. _ set ($ property, $ value)
Function: called when setting undefined attribute values
3. _ isset ($ property)
Function: called when isset () is called for undefined attributes.
4. _ unset ($ property)
Function: called When unset () is called for undefined attributes.
5. _ call ($ method, $ arg_array)
Function: called when an undefined method is called.
The following uses a small program to describe the purpose of these interceptors:
The code is as follows:
Class intercept_demo {
Private $ xingming = "";
Private $ age = 10;
// If an undefined property is accessed, the method corresponding to get {$ property} is called.
Function _ get ($ property ){
$ Method = "get {$ property }";
If (method_exists ($ this, $ method )){
Return $ this-> $ method ();
}
}
// If you set an undefined property value, the method corresponding to set {$ property} is called.
Function _ set ($ property, $ value ){
$ Method = "set {$ property }";
If (method_exists ($ this, $ method )){
Return $ this-> $ method ($ value );
}
}
// If you call the isset method for undefined attributes,
Function _ isset ($ property ){
$ Method = "isset {$ property }";
If (method_exists ($ this, $ method )){
Return $ this-> $ method ();
}
}
// If you call the unset method for undefined attributes,
// 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 "set attribute Name to Li ";
$ Intercept-> Name = "Li ";
Echo "\ $ intercept-> Name = {$ intercept-> Name }";
Echo "isset (Name) = {$ intercept-> testIsset ()}";
Echo "";
Echo "clear attribute Name value ";
Unset ($ intercept-> Name );
Echo "\ $ intercept-> Name = {$ intercept-> Name }";
Echo "";
Echo "calling undefined getAge functions ";
Echo "age = {$ intercept-> getAge ()}";
I hope this article will help you with PHP programming.