Created
November 25, 2013 10:08
-
-
Save Cezarion/7639165 to your computer and use it in GitHub Desktop.
Collection class in PHP
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 | |
| /** | |
| * @title: Simple collection classe in PHP | |
| * @link : http://www.sitepoint.com/collection-classes-in-php/ | |
| */ | |
| class Collection | |
| { | |
| private $items = array(); | |
| public function addItem($obj, $key = null) | |
| { | |
| if ($key == null) | |
| { | |
| $this->items[] = $obj; | |
| } | |
| else | |
| { | |
| if (isset($this->items[$key])) | |
| { | |
| throw new KeyHasUseException("Key $key already in use."); | |
| } | |
| else | |
| { | |
| $this->items[$key] = $obj; | |
| } | |
| } | |
| } | |
| public function deleteItem($key) | |
| { | |
| if (isset($this->items[$key])) | |
| { | |
| unset($this->items[$key]); | |
| } | |
| else | |
| { | |
| throw new KeyInvalidException("Invalid key $key."); | |
| } | |
| } | |
| public function getItem($key) | |
| { | |
| if (isset($this->items[$key])) | |
| { | |
| return $this->items[$key]; | |
| } | |
| else | |
| { | |
| throw new KeyInvalidException("Invalid key $key."); | |
| } | |
| } | |
| public function keys() | |
| { | |
| return array_keys($this->items); | |
| } | |
| public function length() | |
| { | |
| return count($this->items); | |
| } | |
| public function keyExists($key) | |
| { | |
| return isset($this->items[$key]); | |
| } | |
| } | |
| /** | |
| * @usage : | |
| */ | |
| class Salut | |
| { | |
| private $name; | |
| private $number; | |
| public function __construct($name, $number) | |
| { | |
| $this->name = $name; | |
| $this->number = $number; | |
| } | |
| public function __toString() | |
| { | |
| return $this->name . " is number " . $this->number; | |
| } | |
| } | |
| $c = new Collection(); | |
| $c->addItem(new Salut("Steve", 14), "steve"); | |
| $c->addItem(new Salut("Ed", 37), "ed"); | |
| $c->addItem(new Salut("Bob", 49), "bob"); | |
| $c->deleteItem("steve"); | |
| try | |
| { | |
| $c->getItem("steve"); | |
| } | |
| catch (KeyInvalidException $e) | |
| { | |
| print "The collection doesn't contain Steve."; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment