PHP collection class
August 9, 2003 on 2:05 pm | In PHP |Below is a simple collection class that works approximately like Java collection classes.
The usage should be fairly obvious, but you may also refer to the sample code at the end.
Collection.php
1 <?php
2 class Collection {
3 var $elements = array();
4 var $counter = 0;
5 var $pointer = 0;
6
7 function Collection() {
8
9 }
10
11 function add($element) {
12 $this->elements[$this->counter] = $element;
13 $this->counter++;
14 $this->pointer++;
15 }
16
17 function remove($element) {
18 $found = null;
19 for ($i = 0; $i < count($this->elements); $i++) {
20 if ($this->elements[$i] == $element) {
21 $found = $i;
22 }
23 }
24 if ($found != null) {
25 array_splice($this->elements, $found, 1);
26 $this->counter--;
27 $this->pointer--;
28 }
29 }
30
31 function contains($element) {
32 for ($i = 0; $i < count($this->elements); $i++) {
33 if ($this->elements[$i] == $element) {
34 return true;
35 }
36 }
37 return false;
38 }
39
40 function hasNext() {
41 return $this->pointer < $this->counter;
42 }
43
44 function hasPrevious() {
45 return $this->pointer > 0;
46 }
47
48 function next() {
49 return $this->elements[$this->pointer++];
50 }
51
52 function first() {
53 $this->pointer = 0;
54 return $this->elements[$this->pointer];
55 }
56
57 function last() {
58 $this->pointer = $this->counter;
59 return $this->elements[$this->pointer];
60 }
61
62 function previous() {
63 return $this->elements[--$this->pointer];
64 }
65
66 function count() {
67 return count($this->elements);
68 }
69 }
70
71 ?>
Sample
1 <?php
2
3 require_once "Collection.php";
4
5 $collection = new Collection();
6
7 for ($i = 0; $i < 10; $i++) {
8 $element = "Element $i";
9 $collection->add($element);
10 }
11
12 $collection->first();
13 while ($collection->hasNext() ) {
14 $element = $collection->next();
15 echo $element . "n";
16 }
17
18 echo "n";
19
20 $collection->previous();
21 $collection->previous();
22 $collection->remove("Element 7");
23
24 $collection->last();
25 while ($collection->hasPrevious() ) {
26 $element = $collection->previous();
27 echo $element . "n";
28 }
29
30 ?>
Technorati Tags: PHP
Related Posts:
- How to use multiple triggers in RIFE
- Artificial Neural Network in PHP
- Capturing keystrokes with GetAsyncKeyState
- Three Golden Rules to Tackle Complexity
No Comments yet »
RSS feed for comments on this post.
Leave a comment
Powered by blog.mu with Pool theme design by Borja Fernandez.

