ArrayAccessTrait.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. * @property array $data
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @since 2.0
  18. */
  19. trait ArrayAccessTrait
  20. {
  21. /**
  22. * Returns an iterator for traversing the data.
  23. * This method is required by the SPL interface [[\IteratorAggregate]].
  24. * It will be implicitly called when you use `foreach` to traverse the collection.
  25. * @return \ArrayIterator an iterator for traversing the cookies in the collection.
  26. */
  27. public function getIterator()
  28. {
  29. return new \ArrayIterator($this->data);
  30. }
  31. /**
  32. * Returns the number of data items.
  33. * This method is required by Countable interface.
  34. * @return int number of data elements.
  35. */
  36. public function count()
  37. {
  38. return count($this->data);
  39. }
  40. /**
  41. * This method is required by the interface [[\ArrayAccess]].
  42. * @param mixed $offset the offset to check on
  43. * @return bool
  44. */
  45. public function offsetExists($offset)
  46. {
  47. return isset($this->data[$offset]);
  48. }
  49. /**
  50. * This method is required by the interface [[\ArrayAccess]].
  51. * @param int $offset the offset to retrieve element.
  52. * @return mixed the element at the offset, null if no element is found at the offset
  53. */
  54. public function offsetGet($offset)
  55. {
  56. return isset($this->data[$offset]) ? $this->data[$offset] : null;
  57. }
  58. /**
  59. * This method is required by the interface [[\ArrayAccess]].
  60. * @param int $offset the offset to set element
  61. * @param mixed $item the element value
  62. */
  63. public function offsetSet($offset, $item)
  64. {
  65. $this->data[$offset] = $item;
  66. }
  67. /**
  68. * This method is required by the interface [[\ArrayAccess]].
  69. * @param mixed $offset the offset to unset element
  70. */
  71. public function offsetUnset($offset)
  72. {
  73. unset($this->data[$offset]);
  74. }
  75. }