Topics Advanced PHP Features Fibers & SPL Data Structures
advanced 12 min read

Fibers & SPL Data Structures

PHP 8.1 fibers for cooperative multitasking and SPL data structures.

Fibers (PHP 8.1+)

\$fiber = new Fiber(function (): void {
\$value = Fiber::suspend('suspended');
echo "Resumed with: \$value";
});

\$result = \$fiber->start(); // "suspended"
\$fiber->resume('hello'); // "Resumed with: hello"

Fibers allow cooperative multitasking — a fiber can suspend execution and yield control back to the caller.

SPL Data Structures

// SplStack (LIFO)
\$stack = new SplStack();
\$stack->push('first');
\$stack->push('second');
echo \$stack->pop(); // second

// SplQueue (FIFO)
\$queue = new SplQueue();
\$queue->enqueue('first');
\$queue->enqueue('second');
echo \$queue->dequeue(); // first

// SplFixedArray (fixed-size, faster)
\$arr = new SplFixedArray(3);
\$arr[0] = 'a';

Examples

<?php
$stack = new SplStack();
foreach (['a','b','c'] as $v) $stack->push($v);
while (!$stack->isEmpty()) {
    echo $stack->pop() . ' '; // c b a
}

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.