Skip to content

Instantly share code, notes, and snippets.

@amenophis
Created January 12, 2022 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amenophis/b35e689bd8ac4cfef4ec0d98cf0b16ba to your computer and use it in GitHub Desktop.
Save amenophis/b35e689bd8ac4cfef4ec0d98cf0b16ba to your computer and use it in GitHub Desktop.
<?php
class Collection<T>
{
private T[] $items = [];
public function add(T $item): void
{
$this->items[] = $item;
}
public function get(int $index): ?T
{
return $this->items[$index] ?? null;
}
}
$intCollection = new Collection<int>();
$intCollection->add(10); // Valid
$intCollection->add("hello"); // Invalid
$stringCollection = new Collection<string>();
$stringCollection->add(10); // Invalid
$stringCollection->add("hello"); // Valid
<?php
class Collection
{
private $items = [];
public function add($item): void
{
$this->items[] = $item;
}
public function get(int $index):
{
return $this->items[$index] ?? null;
}
}
$intCollection = new Collection();
$intCollection->add(10); // Valid
$intCollection->add("hello"); // Valid
$stringCollection = new Collection();
$stringCollection->add(10); // Valid
$stringCollection->add("hello"); // Valid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment