ArrayAccessTrait.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. /**
  9. * ArrayAccessTrait provides the implementation for `IteratorAggregate`, `ArrayAccess` and `Countable`.
  10. *
  11. * Note that ArrayAccessTrait requires the class using it contain a property named `data` which should be an array.
  12. * The data will be exposed by ArrayAccessTrait to support accessing the class object like an array.
  13. *
  14. * @author Qiang Xue <[email protected]>
  15. * @since 2.0
  16. */
  17. trait ArrayAccessTrait
  18. {
  19. /**
  20. * Returns an iterator for traversing the data.
  21. * This method is required by the SPL interface `IteratorAggregate`.
  22. * It will be implicitly called when you use `foreach` to traverse the collection.
  23. * @return \ArrayIterator an iterator for traversing the cookies in the collection.
  24. */
  25. public function getIterator()
  26. {
  27. return new \ArrayIterator($this->data);
  28. }
  29. /**
  30. * Returns the number of data items.
  31. * This method is required by Countable interface.
  32. * @return integer number of data elements.
  33. */
  34. public function count()
  35. {
  36. return count($this->data);
  37. }
  38. /**
  39. * This method is required by the interface ArrayAccess.
  40. * @param mixed $offset the offset to check on
  41. * @return boolean
  42. */
  43. public function offsetExists($offset)
  44. {
  45. return isset($this->data[$offset]);
  46. }
  47. /**
  48. * This method is required by the interface ArrayAccess.
  49. * @param integer $offset the offset to retrieve element.
  50. * @return mixed the element at the offset, null if no element is found at the offset
  51. */
  52. public function offsetGet($offset)
  53. {
  54. return isset($this->data[$offset]) ? $this->data[$offset] : null;
  55. }
  56. /**
  57. * This method is required by the interface ArrayAccess.
  58. * @param integer $offset the offset to set element
  59. * @param mixed $item the element value
  60. */
  61. public function offsetSet($offset, $item)
  62. {
  63. $this->data[$offset] = $item;
  64. }
  65. /**
  66. * This method is required by the interface ArrayAccess.
  67. * @param mixed $offset the offset to unset element
  68. */
  69. public function offsetUnset($offset)
  70. {
  71. unset($this->data[$offset]);
  72. }
  73. }