SPL essentials

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.

$file = new SplFileObject("data.csv"); foreach ($file as $line) { echo $line; }

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.

$stack = new SplStack(); $stack->push("a"); $queue = new SplQueue(); $queue->enqueue("b"); echo $stack->pop(); echo $queue->dequeue();

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.

$arr = new SplFixedArray(3); $arr[0] = "a"; echo $arr[0]; echo count($arr);

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.

spl_autoload_register(function ($class) { $file = str_replace("\\", "/", $class) . ".php"; echo $file; });

Next: OPcache deep dive

Автор статьи: Arthur Isaev

Изображение баннера