Last active
March 19, 2020 11:22
-
-
Save diloabininyeri/9069d1b3811674c14b7820a90736f67b to your computer and use it in GitHub Desktop.
php collection class with core php it provider you can also be iterated both object and array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class Collection | |
* @noinspection PhpUnused | |
*/ | |
class Collection implements ArrayAccess, IteratorAggregate, JsonSerializable, Countable | |
{ | |
/** | |
* @var array $collection | |
*/ | |
private array $collection; | |
/** | |
* @inheritDoc | |
*/ | |
public function offsetExists($offset): bool | |
{ | |
return isset($this->collection[$offset]); | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function offsetGet($offset) | |
{ | |
return $this->collection[$offset]; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function offsetSet($offset, $value) | |
{ | |
if (empty($offset)) { | |
return $this->collection[] = $value; | |
} | |
return $this->collection[$offset] = $value; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function offsetUnset($offset): void | |
{ | |
unset($this->collection[$offset]); | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function jsonSerialize() | |
{ | |
return serialize($this->collection); | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function count() | |
{ | |
return count($this->collection); | |
} | |
/** | |
* @return array | |
*/ | |
public function __debugInfo() | |
{ | |
return $this->collection; | |
} | |
/** | |
* @return mixed | |
*/ | |
public function first() | |
{ | |
return $this->collection[0]; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function getIterator() | |
{ | |
return new ArrayIterator($this->collection); | |
} | |
/** @noinspection MagicMethodsValidityInspection */ | |
public function __toString() | |
{ | |
return json_encode($this->collection, JSON_THROW_ON_ERROR, 512); | |
} | |
/** | |
* @return mixed | |
*/ | |
public function last() | |
{ | |
return $this->collection[$this->count()-1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
using for example