SPL Structures
SPL structures are ready-made containers from the standard PHP library that hold values in a set order. A stack, a queue and a fixed array each keep a different order.
A stack gives the last value back first
push adds a and then b to the stack here. pop takes b back off, and top then reads a.
<?php
$stack = new SplStack();
$stack->push("a");
$stack->push("b");
echo $stack->pop() . "\n";
echo $stack->top() . "\n";A queue gives the first value back first
enqueue adds first and then second to the queue here. dequeue takes the front value out, so first comes back before second.
<?php
$queue = new SplQueue();
$queue->enqueue("first");
$queue->enqueue("second");
echo $queue->dequeue() . "\n";
echo $queue->dequeue() . "\n";A fixed array keeps its size
SplFixedArray is built with three slots here, and only slot 0 gets a value. The untouched slot 1 dumps as NULL, and the count still prints 3.
<?php
$fixed = new SplFixedArray(3);
$fixed[0] = "x";
echo $fixed[0] . "\n";
var_dump($fixed[1]);
echo count($fixed) . "\n";Example
<?php
$history = new SplStack();
$history->push("home");
$history->push("news");
echo "Current: " . $history->top() . "\n";
$history->pop();
echo "After back: " . $history->top() . "\n";Key points
- A stack works in last-in, first-out order.
- Use push to add a value to a stack and pop to take the top value off.
- top reads the top value of a stack without taking it off.
- A queue works in first-in, first-out order.
- Use enqueue to add a value to a queue and dequeue to take the front value out.
- SplFixedArray holds a fixed count of slots set when it is built.
In this example, the history stack is pushed with home and then news. top reads news as the current page without taking it off. pop removes news, and top then reads home as the page underneath.
Note
An untouched slot in a SplFixedArray holds null until a value is set in that slot.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which class fits values that must come back in first-in, first-out order?