Posted By

Sverri on 09/21/10


Tagged

stack


Versions (?)

Stack class


 / Published in: PHP
 

A rudimentary stack class.

  1. class Stack
  2. {
  3. public $stack = array();
  4.  
  5. public function add($item)
  6. {
  7. $this->stack[] = $item;
  8. return $this;
  9. }
  10. public function next()
  11. {
  12. return array_pop($this->stack);
  13. }
  14. public function count()
  15. {
  16. return ($c = count($this->stack) >= 1) ? $c : 0;
  17. }
  18. public function contains($item, $strict=false)
  19. {
  20. return in_array($item, $this->stack, $strict) ? true : false;
  21. }
  22. public function __get($fn)
  23. {
  24. return $this->$fn();
  25. }
  26. }
  27.  
  28. // EXAMPLE
  29.  
  30. $stack = new Stack();
  31.  
  32. $stack->add('apples')
  33. ->add('oranges')
  34. ->add('pears')
  35. ->add('strawberries');
  36.  
  37. echo '<pre>', print_r($stack), "\n\n";
  38.  
  39. while ($x = $stack->next)
  40. {
  41. echo '$stack->next: "', $x, "\"\n";
  42. }
  43. echo '</pre>';

Report this snippet  

You need to login to post a comment.