So that your PHP object can be foreach, and attributes are modified using Private

Source: Internet
Author: User
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.

  1. /*
  2. * @ Class Sample
  3. * @ 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.
  4. */
  5. Class Sample implements iterator
  6. {
  7. Private $ v1 = '000000 ';
  8. Private $ v2 = 'abc ';
  9. Private $ v3 = array (1, 2, 3 );
  10. Public function rewind ()
  11. {
  12. /*
  13. * Get_object_vars this function can be viewed in the manual.
  14. * Here we implement the defined attributes of the Sample object, instead of combining the dynamically generated attribute $ data into an array,
  15. * Assign this group to $ data
  16. */
  17. $ This-> data = get_object_vars ($ this );
  18. /*
  19. * Point the cursor in the iterator interface to the first element of $ data.
  20. */
  21. Reset ($ this-> data );
  22. }
  23. Public function current () {return current ($ this-> data );}
  24. Public function key () {return key ($ this-> data );}
  25. Public function next () {return next ($ this-> data );}
  26. Public function valid () {return ($ this-> current ()! = False );}
  27. }
  28. $ S = new Sample ();
  29. Foreach ($ s as $ k => $ v) {echo $ k. '='. $ v .'
    ';}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.