A stack with type restricted to int : Stack « Data Structure « PHP






A stack with type restricted to int

<?
class IntStack {  
   var $the_stack;
   var $count = 0;
   
   function push ($intvar) {
      if (is_integer($intvar)) {
          $this->the_stack[$this->count] = $intvar; 
          $this->count++;
          print("Push of $intvar succeeded.<BR>");
      } else {
        print("Hey, IntStack is for ints only!<BR>");
      }
   }
   function pop () {
      if ($this->count > 0) {
          $this->count--; // decrement count
          $top = $this->the_stack[$this->count];
          return($top);
      } else {
        print("Hey, the stack is empty!<BR>");
      }
   }
}
 
 
$my_stack = new IntStack;
$my_stack->push(1);
$my_stack->push(49);
$my_stack->push("A");

$pop_result = $my_stack->pop();
print("Top of the stack was $pop_result<BR>");

$pop_result = $my_stack->pop();
print("Top of the stack was $pop_result<BR>");

$pop_result = $my_stack->pop(); 
print("Top of the stack was $pop_result<BR>");


?>
           
       








Related examples in the same category

1.array_pop: Pop the element off the end of array
2.array_push: Push one or more elements onto the end of array
3.Stack in Use