If you want to set attributes of an object one by one, it will be troublesome. In this case, you can use the processor functions of the object _ get () and _ set (), however, to use these two methods, the attribute must be protect or private, as shown in the following example:
| The Code is as follows: |
Copy code |
Class Person
{
Private $ __data = array ();
Public function _ get ($ property)
{
If (isset ($ this->__ data [$ property])
{
Return $ this->__ data [$ property];
}
Else
{
Return false;
}
}
Public function _ set ($ property, $ value)
{
$ This->__ data [$ property] = $ value;
}
}
|
The _ set () and _ get () methods are for the protect or private attributes. In this way, the attribute cannot be directly accessed from outside, but the _ set () method defined by the public () and the _ get () method can be easily accessed. colleagues' two methods have a high universality for Attribute operations, and can also restrict the validity of object attributes, only attributes in the $ __data array can be set to prevent external users from setting attributes directly. However, using _ set () and _ get () also has some shortcomings. First, these two methods only capture private or protected attributes, that is, attributes with no access permission from the outside, so php will report a fatal error. Second, these two methods undermine the inheritance of attributes. If the parent object has a _ set () method and implements its own _ get () method in the subclass, the object will not run normally, because the _ get () method of the parent object cannot be called forever, and it cannot be used to check whether the overwritten attribute exists because it does not call the _ get () method. We can see that someone has solved the above problem by implementing _ isset () and _ unset. The Code is as follows:
| The Code is as follows: |
Copy code |
Public function _ isset ($ property)
{
If (isset ($ this-> data [$ property])
{
Return true;
}
Else
{
Return false;
}
}
Public function _ unset ($ property)
{
If (isset ($ this-> data [$ property])
{
Return unset ($ this-> data [$ property]);
}
Else
{
Return false;
}
}
|
Using _ isset () and _ unset () ensures the existence of attributes. However, these two methods are only valid after PHP5.1.