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...