Well, what do you mean by vector, then? Traditionally, "vector" is pretty much synonymous with "array".
If you need accessor functions of an object, such as push, pop, top, is_empty, etc... (which more define a stack, queue, or deque container), then you can write these using a standard PHP array.
class Stack
{
var $st; // the stack
function Stack()
{
$st = array();
}
function size()
{
return count($this->st);
}
function is_empty()
{
return $this->size() == 0;
}
// add a new item to the stack
function push($item)
{
$st[] = $item;
}
// get the item on the top of the stack (without removing it)
function top()
{
$ret = FALSE;
if (! $this->is_empty())
{
$ret = $this->st[$this->size() - 1];
}
return $ret;
}
// remove item from the stack
function pop()
{
$ret = $this->top();
if (! $this->is_empty())
{
unset($this->st[$this->size() - 1]);
}
}
}
Note that I didn't test this code -- I just typed it into the reply window. But it should give you an idea of how to write your own data types using existing primitive types.
Also, you should notice the inherent problem with normal function semantics, that is, that functions can only return one value.
Our functions return FALSE when there's a problem (e.g. popping an empty stack). PHP doesn't let you throw exceptions, so we return FALSE to signify a problem. "So what?" you ask? Well, what if the stack actually contained the value FALSE? In that case, you can't distinguish from a valid or invalid operation.
This is why many C functions use pointers to set an out parameter, and use the return value for error codes.
In PHP, we can use references to achieve the same thing:
class Stack
{
var $st; // the stack
function Stack()
{
$st = array();
}
function size()
{
return count($this->st);
}
function is_empty()
{
return $this->size() == 0;
}
// add a new item to the stack
function push($item)
{
$st[] = $item;
}
// get the item on the top of the stack (without removing it)
function top(& $item)
{
$ret = FALSE;
if (! $this->is_empty())
{
$item = $this->st[$this->size() - 1];
$ret = TRUE;
}
return $ret;
}
// remove item from the stack
function pop(& $item)
{
$ret = FALSE;
if (! $this->is_empty())
{
$item = $this->top();
unset($this->st[$this->size() - 1]);
$ret = TRUE;
}
}
}
See the difference? We pass in $item as a reference to our functions, and assign our real return value to it. We use the function return value as an error check -- we return FALSE if there's a problem, and TRUE if everything's okay.
Take care,
Nik
http://www.bigaction.org/