Basic Stack Class Example

by randy melder @ gmail.com

Find documentation for this example at: http://www.randymelder.com/2009/12/05/php_stack/

/*
 * Stack - the objective of this class is to demonstrate a 
 * basic stack data structure in PHP without using the 
 * built in array functions if possible.
 */

class Stack {
	
	var $maxsize;
	var $items; 
	
	/*
	 * 
	 */
	function __construct($maxsize = 10)
	{
		$this->maxsize = $maxsize;
		$this->items = array();
	}
	
	/*
	 * Add an element to the top of the stack.
	 */
	function push($data = NULL) {
		if(sizeof($this->items) >= $this->maxsize)
		{
			echo "Potential stack overflow detected.";
			return 0;
		}
		$this->items[] = $data;
		return 1;
	}
	
	/*
	 * Remove the top element of the stack.
	 */
	function pop() {
		$tmp_array = array();
		$size = sizeof($this->items);
		for($i = 0; $i < ($size - 1); $i++)
		{
			$tmp_array[] = $this->items[$i];
		}
		$this->items = $tmp_array;
	}

}

}

// Let's see a trivial implementation...
$s = new Stack(3);
echo "
initial "; var_dump($s->items); $s->push("Mark"); echo "
push "; var_dump($s->items); echo "
push "; $s->push("Wes"); var_dump($s->items); echo "
push "; $s->push("MJ"); var_dump($s->items); echo "
push "; $s->push("Bruce"); var_dump($s->items); echo "
pop "; $s->pop(); var_dump($s->items); echo "
pop "; $s->pop(); var_dump($s->items); echo "
pop "; $s->pop(); var_dump($s->items); echo "
pop "; $s->pop(); var_dump($s->items);
// Let's see a trivial implementation...
initial array(0) { }
push array(1) { [0]=> string(4) "Mark" }
push array(2) { [0]=> string(4) "Mark" [1]=> string(3) "Wes" }
push array(3) { [0]=> string(4) "Mark" [1]=> string(3) "Wes" [2]=> string(2) "MJ" }
push Potential stack overflow detected.array(3) { [0]=> string(4) "Mark" [1]=> string(3) "Wes" [2]=> string(2) "MJ" }
pop array(2) { [0]=> string(4) "Mark" [1]=> string(3) "Wes" }
pop array(1) { [0]=> string(4) "Mark" }
pop array(0) { }
pop array(0) { }