PHP SPL ArrayAccess Iterator countable class


/ Published in: PHP
Save to your folder(s)

use an object as an array


Copy this code and paste it in your HTML
  1. class array_test implements ArrayAccess, Iterator, Countable
  2. {
  3. private $container = array();
  4.  
  5. public function __construct() {}
  6.  
  7. /*
  8. * to use ArrayAccess
  9. */
  10. public function offsetSet($offset,$value)
  11. {
  12. if ($offset == "")
  13. {
  14. $this->container[] = $value;
  15. }
  16. else
  17. {
  18. $this->container[$offset] = $value;
  19. }
  20. }
  21.  
  22. /*
  23. * to use ArrayAccess
  24. */
  25. public function offsetExists($offset)
  26. {
  27. return isset($this->container[$offset]);
  28. }
  29.  
  30. /*
  31. * to use ArrayAccess
  32. */
  33. public function offsetUnset($offset)
  34. {
  35. unset($this->container[$offset]);
  36. }
  37.  
  38. /*
  39. * to use ArrayAccess
  40. */
  41. public function offsetGet($offset)
  42. {
  43. return isset($this->container[$offset]) ? $this->container[$offset] : null;
  44. }
  45.  
  46. /*
  47. * to use Iterator
  48. */
  49. public function rewind()
  50. {
  51. reset($this->container);
  52. }
  53.  
  54. /*
  55. * to use Iterator
  56. */
  57. public function current()
  58. {
  59. return current($this->container);
  60. }
  61.  
  62. /*
  63. * to use Iterator
  64. */
  65. public function key()
  66. {
  67. return key($this->container);
  68. }
  69.  
  70. /*
  71. * to use Iterator
  72. */
  73. public function next()
  74. {
  75. return next($this->container);
  76. }
  77.  
  78. /*
  79. * to use Iterator
  80. */
  81. public function valid()
  82. {
  83. return $this->current() !== false;
  84. }
  85.  
  86. /*
  87. * to use Countable
  88. */
  89. public function count()
  90. {
  91. return count($this->container);
  92. }
  93. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.