Administrateur PHPfrance |
3088 Messages
11 déc. 2006, 04:00
Voici une classe que j'utilise assez souvent, à chaque fois que j'ai besoin d'une pile en fait.
class stack
{
private $stack = array();
/**
* Pop the top element off the stack
*
* @return mixed The top element
*/
public function pop()
{
return array_pop($this->stack);
}
/**
* Shift an element off the bottom of the stack
*
* @return mixed The bottom element
*/
public function shift()
{
return array_shift($this->stack);
}
/**
* Add an element at the top of the stack
*
* @param mixed $elem The element to add
* @return void
*/
public function push($elem)
{
array_push($this->stack, $elem);
}
/**
* Add an element at the bottom of the stack
*
* @param mixed $elem The elementt to add
* @return void
*/
public function unshift($elem)
{
array_unshift($this->stack, $elem);
}
/**
* Return the top element without removing from the stack
*
* @return mixed The top element, or FALSE if the array is empty
*/
public function peek()
{
return (!empty($this->stack)) ? end($this->stack) : FALSE;
}
/**
* Return the contents of the stack
*
* @return array The stack, ordered from the bottom up
*/
public function get()
{
return $this->stack;
}
/**
* Test whether given element is in the stack
*
* @param mixed $elem The element
* @return bool
*/
public function search($elem)
{
return in_array($elem, $this->stack, TRUE);
}
/**
* Return the number of elements in the stack
*
* @return integer
*/
public function count()
{
return count($this->stack);
}
/**
* Return the position of the element within the stack
*
* Returns the 0-based position of the element (starting from the top) if it is within the stack,
* or FALSE otherwise
*
* @param mixed $elem The element
* @return mixed Position of the element, or FALSE
*/
public function pos($elem)
{
$pos = array_search($elem, $this->stack, TRUE);
if (!$pos && is_bool($pos))
{
return FALSE;
}
return count($this->stack) - $pos - 1;
}
}
En général on n'utilise que push(), pop() et peek() mais j'ai ajouter les autres fonctions par soucis de perfection. Exemples rapides :
$stack = new stack;
$stack->push('un');
$stack->push('deux');
// affiche 'deux'
echo $stack->peek(), "\n";
// affiche '0'
echo $stack->pos('deux'), "\n";
// affiche '1'
echo $stack->pos('un'), "\n";
// affiche 'deux' aussi
echo $stack->pop(), "\n";
// affiche 'un'
echo $stack->peek(), "\n";
// affiche '1'
echo $stack->count(), "\n";