A sneak peak at some new SPL data structures (stack, heap, queue, list) introduced in PHP 5.3.
Following my recent experiments with the new SPL features in PHP 5.3, I saw that there are some new SPL data structures: heap, stack, queue and linked list. They aren't documented yet but I had a peek at the C sources.
The first class, SplStack, is a standard implementation of a stack (duh!).
$stack = new SplStack();
$stack->push('b');
$stack->push('a');
$stack->push('c');
echo $stack->pop()."\n";
echo $stack->pop()."\n";
echo $stack->pop()."\n";
// OUTPUT:
// c
// a
// bThe second class is SplHeap, which is an abstract class and can't be instantiated directly.
Two of its child classes are SplMinHeap (which sorts the data in descending order) and SplMaxHeap (which sorts the data in ascending order).
$heap = new SplMaxHeap();
$heap->insert('b');
$heap->insert('a');
$heap->insert('c');
echo $heap->extract()."\n";
echo $heap->extract()."\n";
echo $heap->extract()."\n";
// OUTPUT:
// c
// b
// a$heap = new SplMinHeap();
$heap->insert('b');
$heap->insert('a');
$heap->insert('c');
echo $heap->extract()."\n";
echo $heap->extract()."\n";
echo $heap->extract()."\n";
// OUTPUT:
// a
// b
// cAnother SplHeap-derived class is SplPriorityQueue, which sorts the data by priority.
With the setExtractFlags() method, you can choose what to extract:
$pqueue = new SplPriorityQueue();
$pqueue->setExtractFlags(SplPriorityQueue::EXTR_DATA);
$pqueue->insert('low', 1);
$pqueue->insert('top', 3);
$pqueue->insert('medium', 2);
echo 'TOP ELEMENT: '.$pqueue->top()."\n";
echo $pqueue->extract()."\n";
echo $pqueue->extract()."\n";
echo $pqueue->extract()."\n";
// OUTPUT:
// TOP ELEMENT: top
// top
// medium
// low$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
echo 'TOP: '.$list->top()."\n";
echo 'BOTTOM: '.$list->bottom()."\n";
// OUTPUT:
// TOP: c
// BOTTOM: a
echo "FIFO:\n";
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO);
for ($list->rewind(); $list->valid(); $list->next()) {
echo $list->current()."\n";
}
// OUTPUT:
// FIFO:
// a
// b
// c
echo "LIFO:\n";
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
for ($list->rewind(); $list->valid(); $list->next()) {
echo $list->current()."\n";
}
// OUTPUT:
// LIFO:
// c
// b
// a
Lorenzo
Leave a reply