Implementing a stack using PHP array

First, we will create an interface for the stack so that we can use it in different implementations, and can ensure that all implementations have some similarity to each other. Let us write the simple interface for the stack:

interface Stack { 

public function push(string $item);

public function pop();

public function top();

public function isEmpty();

}

As we can see from the preceding interface, we kept all stack functions inside the interface because the class that it is implementing must have all these mentioned functions, otherwise, else a fatal error will be thrown during runtime. Since we are implementing the stack using a PHP array, we are going to use some existing PHP functions for push, pop, and top operations. We are going to implement the stack in such a way that we can define the size of the stack. If there is no item in the array and we still want to pop, it will throw an underflow exception, and if we try to push more items than its capacity allows, then an overflow exception will be thrown. Here is the code for a stack implementation using an array:

class Books implements Stack { 

private $limit;
private $stack;

public function __construct(int $limit = 20) {
$this->limit = $limit;
$this->stack = [];
}

public function pop(): string {

if ($this->isEmpty()) {
throw new UnderflowException('Stack is empty');
} else {
return array_pop($this->stack);
}
}

public function push(string $newItem) {

if (count($this->stack) < $this->limit) {
array_push($this->stack, $newItem);
} else {
throw new OverflowException('Stack is full');
}
}

public function top(): string {
return end($this->stack);
}

public function isEmpty(): bool {
return empty($this->stack);
}
}

Now let us go through the code we have written for the stack. We named the stack implementation Books, but we can name it anything we want as long as it's a valid class name. First, we construct the stack using the __construct() method with an option to limit the number of items we can store in the stack. The default value is set at 20. The next method defines the pop operation:

public function pop():  string { 

if ($this->isEmpty()) {
throw new UnderflowException('Stack is empty');
} else {
return array_pop($this->stack);
}
}

The pop method will return a string if the stack is not empty. We use the empty method we defined in the stack class for this purpose. If the stack is empty, we throw an UnderFlowException from SPL. If there is no item to pop, we can prevent that operation from taking place. If the stack is not empty, we use the array_pop function from PHP to return the last item from the array.

In the push method, we do the opposite of pop. First, we check whether or not the stack is full. If it is not, we add the string item at the end of the stack using the array_push function of PHP. If the stack is full, we throw an OverFlowException from SPL. The top method returns the top most element of the stack. The isEmpty method checks whether or not the stack is empty.

Since we are following PHP 7, we are using both scalar type declarations at method level and return types for methods.

In order to use our just implemented stack class, we have to think of an example where we can use all these operations. Let us write a small program to make a book stack. Here is the code for this:

try { 
$programmingBooks = new Books(10);
$programmingBooks->push("Introduction to PHP7");
$programmingBooks->push("Mastering JavaScript");
$programmingBooks->push("MySQL Workbench tutorial");
echo $programmingBooks->pop()." ";
echo $programmingBooks->top()." ";
} catch (Exception $e) {
echo $e->getMessage();
}

We have created an instance for our book stack, and for keeping our programming book titles in it. We have three push operations. The last inserted book name is "MySQL workbench tutorial". If we pop after three push operations, we will have this title name as the return. After that, the top will return "Mastering JavaScript", which will become the top item once the pop operation has been performed. We are nesting the whole code in a try...catch block so that we can handle the exception thrown by the overflow and underflow. The preceding code will have the following output:

MySQL Workbench tutorial
Mastering JavaScript

Now let us focus on the complexities of the different stack operations we have just completed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset