Home > Backend Development > PHP Tutorial > Make your PHP object available foreach and modify the properties with Private

Make your PHP object available foreach and modify the properties with Private

WBOY
Release: 2016-07-25 09:06:33
Original
976 people have browsed it
Play it when you are bored.
Traversing an object is actually just traversing a specific array type attribute in the object.
After PHP5, you can directly foreach, but the private members of the class cannot be accessed.
The object-oriented principle also does not allow class members to be directly accessed from the outside.
  1. /*
  2. * @class Sample
  3. * @remark The traversal object is actually just an array in the variable object; to enable the object to be traversed, the iterator interface needs to be implemented
  4. */
  5. class Sample implements iterator
  6. {
  7. private $v1 = '123';
  8. private $v2 = 'abc';
  9. private $v3 = array( 1, 2, 3 );
  10. public function rewind()
  11. {
  12. / *
  13. * get_object_vars Check the manual for this function to see its functions
  14. * Here, the Sample object implements the defined attributes instead of the dynamically generated attributes $data into an array,
  15. * Assign the 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.'
    ';}
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template