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, the premise of using these two methods is that the attribute must be protect or private,
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 instance code is as follows:
- 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 directly setting attributes. 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 destroy 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 obtained to check whether the overwritten attribute exists because it does not call the _ get () method. we can see that the above problem is solved by implementing _ isset () and _ unset. the code is as follows:
The instance code is as follows:
- 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.