So that your PHP object can be foreach, and attributes are modified using Private
If you are bored, you can play with it. The traversal object is actually just a specific attribute of the array type in the object. You can use foreach directly after PHP5, but private members of the class cannot access it. The object-oriented principle does not allow class members to be directly accessed from outside.
- /*
- * @ Class Sample
- * @ Remark: the traversal object is actually an array of the variable in the object. to make the object be traversed, the iterator interface must be implemented.
- */
- Class Sample implements iterator
- {
- Private $ v1 = '000000 ';
- Private $ v2 = 'abc ';
- Private $ v3 = array (1, 2, 3 );
- Public function rewind ()
- {
- /*
- * Get_object_vars this function can be viewed in the manual.
- * Here we implement the defined attributes of the Sample object, instead of combining the dynamically generated attribute $ data into an array,
- * Assign this group to $ data
- */
- $ This-> data = get_object_vars ($ this );
- /*
- * Point the cursor in the iterator interface to the first element of $ data.
- */
- Reset ($ this-> data );
- }
- Public function current () {return current ($ this-> data );}
- Public function key () {return key ($ this-> data );}
- Public function next () {return next ($ this-> data );}
- Public function valid () {return ($ this-> current ()! = False );}
- }
- $ S = new Sample ();
- Foreach ($ s as $ k => $ v) {echo $ k. '='. $ v .'
';}
|