/ Published in: PHP
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php class Collection { private $items; private $attributes; public function __construct() { $this->attributes['Count'] = 0; $this->attributes['IsFixedSize'] = false; $this->attributes['FixedSize'] = 0; $this->attributes['IsReadOnly'] = false; } public function __get($var) { return $this->attributes[$var]; } else { throw new Exception("The property {$var} does not exist", 0); } } public function __set($var, $value) { $this->attributes[$var] = $value; } else { throw new Exception("The property {$var} cannot be set as it does not exist", 0); } } public function Add($item) { if($this->IsFixedSize) { $this->items[] = $item; } else { throw new Exception("Cannot not add more items to collection. Max size is {$this->FixedSize}", 0); } } else if($this->IsReadOnly) { throw new Exception("Cannot add item to a read only collection", 0); } else { $this->items[] = $item; } } foreach($items as $item) { self::Add($item); } } public function Contains($item) { foreach($this->items as $i) { if($i == $item) { return true; } } return false; } public function Get($index) { if(key_exsits($index, $this->items)) { return $this->items[$index]; } return false; } public function GetCollectionAsArray() { return $this->items; } public function GetCollectionAsString() { } public function IndexOf($item, $startIndex = 0) { if($this->items[$i] == $item) { return $i; break; } } return -1; } public function LastIndexOf($item) { $lastIndex = -1; if($this->items[$i] == $item) { $lastIndex = $i; } } return $lastIndex; } public function Insert($index, $item) { if($this->IsFixedSize) { if($index < $this->FixedSize) { $this->items[$index] = $item; } else { throw new Exception("Cannot insert item at {$index}. Max size is {$this->FixedSize}", 0); } } else if($this->IsReadOnly) { throw new Exception("Cannot insert an item into a read only collection", 0); } else { $this->items[$index] = $item; } } public function Remove($item) { $index = self::IndexOf($item); self::RemoveAt($index); } public function RemoveAt($index) { if(!$this->IsReadOnly) { } else { throw new Exception("Index out of range. The index {$index} is out of range of the collection", 0); } } else { throw new Exception("Cannot remove item from read only collection", 0); } } public function RemoveRange($startIndex, $endIndex) { for($i = $startIndex; $i < $endIndex; $i++) { self::RemoveAt($i); } } } } ?>