SPL essentials
The standard PHP library ships ready classes for the jobs everybody writes by hand, and PHP has them without an extension. The four examples below build what they use, so each list, count and class name on the page came out of a run.
SplFileObject
Class SplFileObject wraps a file in an object you can loop over. Each iteration yields one line without loading the whole file.
It works well for logs and CSV exports. Add flags when you need to skip empty lines or read CSV rows directly.
<?php file_put_contents(__DIR__ . "/data.csv", "Ada,1\nBob,2"); $file = new SplFileObject(__DIR__ . "/data.csv"); foreach ($file as $line) { echo trim($line), PHP_EOL; }
php lines.php
Ada,1
Bob,2
The loop reads one line per pass and the object keeps the position itself, so no array of lines is built.
SplStack and SplQueue
A stack returns items last in first out, while a queue returns them first in first out. SPL ships both as ready classes.
Use a stack for undo history and a queue for jobs waiting in order. Both keep pointer logic out of your code.
<?php $stack = new SplStack(); $stack->push("a"); $stack->push("b"); $queue = new SplQueue(); $queue->enqueue("c"); $queue->enqueue("d"); echo $stack->pop(), PHP_EOL; echo $queue->dequeue(), PHP_EOL; echo count($stack), " ", count($queue), PHP_EOL;
php lists.php
b
c
1 1
The stack gave back the value pushed last, the queue the value queued first, and each class keeps the rest of its items for the next call.
SplFixedArray
Class SplFixedArray holds a fixed number of slots. It uses less memory than a normal array for large numeric lists.
Set the size once at creation, then fill slots by index. Resize only when you truly need a new length.
<?php $arr = new SplFixedArray(3); $arr[0] = "a"; $arr[1] = "b"; $arr->setSize(4); echo $arr[0], PHP_EOL; echo count($arr), PHP_EOL;
php fixed.php
a
4
The value sits at index zero as written, and the resize changed the length without touching the values already stored.
spl_autoload_register
Function spl_autoload_register loads class files on demand. PHP calls your loader the first time an unknown class name appears.
Map class names to file paths inside the callback. Modern projects let Composer generate this mapping instead.
<?php file_put_contents( __DIR__ . "/Widget.php", "<?php\nclass Widget\n{\n public function name(): string\n {\n return \"widget\";\n }\n}\n" ); spl_autoload_register(function (string $class): void { $file = __DIR__ . "/" . $class . ".php"; if (is_file($file)) { require $file; } }); $widget = new Widget(); echo get_class($widget), PHP_EOL; echo $widget->name(), PHP_EOL;
php autoload.php
Widget
widget
The class file was written but never required by the program: the loader found it when new Widget() asked for a class nobody had declared yet.
Exercises
- Add a third line to the file example and confirm the loop prints three lines.
- Push two values onto the stack and pop them both, then read the count.
- Shrink the fixed array back to two slots and read the count.
- Add a second class file and instantiate both through the same loader.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does an
SplFileObjectgive you in aforeachloop?Answer
One whole line per iteration
The object keeps the file position and yields the next line each time.
-
Which class returns items last in, first out?
Answer
SplStackSplStack::pop()takes the item pushed last, which is the LIFO order. -
What does
setSize()change on anSplFixedArray?Answer
The number of slots
The class has a fixed length, and
setSize()is the one call that changes it. -
When does PHP call a function registered with
spl_autoload_register()?Answer
When a class is used and not yet declared
The loader is the last resort before PHP gives up with a class not found error.
-
What does this program print?
<?php $stack = new SplStack(); $stack->push(1); $stack->push(2); echo $stack->pop();Answer
2
A stack hands back the value that went in last.
-
What does this program print?
<?php $queue = new SplQueue(); $queue->enqueue("first"); $queue->enqueue("second"); echo $queue->dequeue();Answer
first
A queue serves the oldest item first, so the first value leaves first.
-
What does this program print?
<?php $arr = new SplFixedArray(2); $arr[0] = "a"; $arr->setSize(3); echo count($arr);Answer
3
The resize sets the length to three, and the value at index zero stays where it was.
-
What does this program print, run in an empty folder?
<?php file_put_contents(__DIR__ . "/data.csv", "Ada,1\nBob,2"); $file = new SplFileObject(__DIR__ . "/data.csv"); $count = 0; foreach ($file as $line) { $count++; } echo $count;Answer
2
The file holds two lines and no trailing break, so the loop yields exactly two.
-
A class name in an autoloader comes from outside the program. What must the loader never do with it?
Answer
Glue it into a path without checking that the file stays in the class folder
A name such as
..\..\etc\passwdbecomes a path, so the loader has to keep the result inside its folder. -
Why does the fixed array use less memory than a normal array for large numeric lists?
Answer
It has a set length, so it needs no hash table for the keys
The slots are numbered and the length is fixed, which removes the per key bookkeeping a PHP array carries.
The examples call spl_autoload_register(), is_file(), count() and get_class(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.
Article author: Arthur Isaev