|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SubjectivePHP\Spl\Traits; |
|
4
|
|
|
|
|
5
|
|
|
trait ArrayAccessTrait |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* Sets the value at the specified index $offset to $value |
|
9
|
|
|
* |
|
10
|
|
|
* @param string|integer $offset The index being set. |
|
11
|
|
|
* @param mixed $value The new value for the index. |
|
12
|
|
|
* |
|
13
|
|
|
* @return void |
|
14
|
|
|
* |
|
15
|
|
|
* @throws \InvalidArgumentException Thrown if $offset is not null, an integer or a string. |
|
16
|
|
|
*/ |
|
17
|
|
|
public function offsetSet($offset, $value) |
|
18
|
|
|
{ |
|
19
|
|
|
if ($offset === null) { |
|
20
|
|
|
$this->container[] = $value; |
|
|
|
|
|
|
21
|
|
|
return; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
if (!is_string($offset) && !is_int($offset)) { |
|
25
|
|
|
throw new \InvalidArgumentException('$offset must be an integer or string'); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
$this->container[$offset] = $value; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Returns whether the requested index exists. |
|
33
|
|
|
* |
|
34
|
|
|
* @param mixed $offset The index being checked. |
|
35
|
|
|
* |
|
36
|
|
|
* @return boolean |
|
37
|
|
|
*/ |
|
38
|
|
|
public function offsetExists($offset) |
|
39
|
|
|
{ |
|
40
|
|
|
if (is_string($offset) || is_int($offset)) { |
|
41
|
|
|
return array_key_exists($offset, $this->container); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return false; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Unsets the value at the specified index |
|
49
|
|
|
* |
|
50
|
|
|
* @param mixed $offset The index being unset. |
|
51
|
|
|
* |
|
52
|
|
|
* @return void |
|
53
|
|
|
*/ |
|
54
|
|
|
public function offsetUnset($offset) |
|
55
|
|
|
{ |
|
56
|
|
|
if (is_string($offset) || is_int($offset)) { |
|
57
|
|
|
unset($this->container[$offset]); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Returns the value at the specified index. |
|
63
|
|
|
* |
|
64
|
|
|
* @param integer|string $offset The index with the value. |
|
65
|
|
|
* |
|
66
|
|
|
* @return mixed |
|
67
|
|
|
* |
|
68
|
|
|
* @throws \InvalidArgumentException Thrown if $offset is not null, an integer or a string. |
|
69
|
|
|
*/ |
|
70
|
|
|
public function offsetGet($offset) |
|
71
|
|
|
{ |
|
72
|
|
|
if (!is_string($offset) && !is_int($offset)) { |
|
73
|
|
|
throw new \InvalidArgumentException('$offset must be an integer or string'); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
return array_key_exists($offset, $this->container) ? $this->container[$offset] : null; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: