I am learning PHP 7 and decided to implement a simple FIFO singly-linked queue in it:
<?php
class QueueNode {
var $item;
var $next;
function __construct($item) {
$this->item = $item;
}
function get_item() {
return $this->item;
}
}
class Queue {
var $head;
var $tail;
var $size;
function push($item) {
if ($this->size == 0) {
$this->head = $this->tail = new QueueNode($item);
} else {
$new_node = new QueueNode($item);
$this->tail->next = $new_node;
$this->tail = $new_node;
}
$this->size++;
}
function pop() {
if ($this->size == 0) {
throw new Exception("Popping from an empty queue.");
}
$ret = $this->head->item;
$this->head = $this->head->next;
if (--$this->size == 0) {
$this->head = $this->tail = null;
}
return $ret;
}
}
$queue = new Queue();
for ($i = 1; $i <= 10; $i++) {
$queue->push($i);
}
for ($i = 1; $i <= 10; $i++) {
echo $queue->pop() . " ";
}
echo "<br>";
?>
As always, any critique is much appreciated.