You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.3KB

  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 integer 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 boolean
  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 integer $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 integer $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. }