Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Last active March 19, 2020 11:22
Show Gist options
  • Save diloabininyeri/9069d1b3811674c14b7820a90736f67b to your computer and use it in GitHub Desktop.
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
<?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];
}
}
@diloabininyeri
Copy link
Author

diloabininyeri commented Mar 19, 2020

using for example

<?php

$collections = new Collection();

$collections[] =12;

$collections[] = 14;
$collections[] = 145;
$collections[] =4;


print_r($collections);


echo $collections;

echo $collections->last();

echo $collections->first();

foreach ($collections as $collection)
{
    echo $collection;
}

count($collections);


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment