Enables your PHP object to be foreach, with the property being decorated with private

Source: Internet
Author: User
Play a game when you are bored.
Traversing an object is simply a matter of iterating through the properties of a particular array type in the object.
PHP5 can be directly foreach, but private members of the class cannot access it.
The object-oriented principle also does not allow class members to be directly accessed externally.
  1. /*
  2. * @class Sample
  3. * @remark traversing an object is simply an array of variables in that object; To enable the object to be traversed, implement the iterator interface
  4. */
  5. Class Sample implements iterator
  6. {
  7. Private $v 1 = ' 123 ';
  8. Private $v 2 = ' abc ';
  9. Private $v 3 = Array (1, 2, 3);
  10. Public Function Rewind ()
  11. {
  12. /*
  13. * Get_object_vars This function check the manual to see its function
  14. * Here the sample object implementation of the defined properties, rather than dynamically generated properties $data merged into an array,
  15. * Assign this group to $data
  16. */
  17. $this->data = Get_object_vars ($this);
  18. /*
  19. * Point a cursor in the iterator interface to the first element of the $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. '
    ';}
Copy Code
  • 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.