CodyKochmann
2/25/2016 - 8:04 PM

stack class in php

stack class in php

class stack
{
  public function __construct()
  {
    $this->collection=array();
  }

  public function get_collection()
  {
    return $this->collection;
  }

  public function set_collection(array $o=array())
  {
    $this->collection=$o;
    return TRUE;
  }

  public function length()
  {
    return count($this->collection);
  }

  public function push($o)
  {
    $this->collection[$this->length]=$o;
    return $this->collection;
  }

  public function append($o)
  {
    return $this->push($o);
  }

  public function merge(array $o=array())
  {
    $this->collection=array_merge($this->collection,$o);
    return $this->collection;
  }

  public function pop()
  {
    if(empty($this->collection)){
      throw new Exception('Trying to pop an empty stack.');
    } else {
      return array_pop($this->collection);
    }
  }

  public function shift()
  {
    if(empty($this->collection)){
      throw new Exception('Trying to shift an empty stack.');
    } else {
      return array_shift($this->collection);
    }
  }

  public function peek()
  {
    if(empty($this->collection)){
      throw new Exception('Trying to pop an empty stack.');
    } else {
      return end($this->collection);
    }
  }

  public function top()
  {
    return $this->peek();
  }

  public function bottom()
  {
    return $this->collection[0];
  }

  public function sort()
  {
    sort($this->collection);
    return $this->collection;
  }

  public function shuffle()
  {
    shuffle($this->collection);
    return $this->collection;
  }

  public function is_empty()
  {
    return empty($this->collection);
  }
}