Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

La Fiber lance là où elle se trouve

<?php

// Illustrates: $fiber->throw($exception) resumes the fiber and raises the
// exception exactly where Fiber::suspend() paused it, not in the caller's scope.

$fiber = new Fiber(function (): void {
    echo "fiber: starting
";

    try {
        $value = Fiber::suspend('paused, waiting for input');
        echo "fiber: resumed normally with '{$value}'
";
    } catch (RuntimeException $e) {
        // This ordinary try/catch, wrapped around suspend(), catches the
        // exception injected by Fiber::throw() -- no special API needed.
        echo "fiber: caught injected exception: '{$e->getMessage()}'
";
    }

    echo "fiber: finishing
";
});

echo "main: getCurrent() outside any fiber is: ";
var_dump(Fiber::getCurrent());

$suspendedValue = $fiber->start();
echo "main: fiber suspended with '{$suspendedValue}'
";

// This does NOT throw here, in main's scope. It resumes the fiber and the
// exception surfaces at the suspend() call above, inside the fiber's body.
$fiber->throw(new RuntimeException('something went wrong'));

echo "main: fiber finished? " . ($fiber->isTerminated() ? 'yes' : 'no') . "
";

// Starting an already-started (and now terminated) fiber is not a silent
// no-op: it throws a FiberError.
try {
    $fiber->start();
} catch (FiberError $e) {
    echo "main: caught FiberError: '{$e->getMessage()}'
";
}

Fiber est la petite sœur du générateur pour laquelle personne n’écrit d’astuces, en voici donc une.

$fiber->throw($exception) ne lance pas d’exception dans le contexte de l’appelant. Elle reprend la fibre suspendue et lève l’exception exactement à l’appel Fiber::suspend() qui l’avait mise en pause, comme si cet appel lui-même avait levé l’exception.

Cela signifie qu’un simple try/catch écrit autour de l’appel suspend() dans le corps de la fibre l’attrapera, sans besoin d’API spéciale côté fibre.

Notez aussi que Fiber::getCurrent() retourne null en dehors de toute fibre, et que démarrer une fibre déjà démarrée lève une FiberError, et non une opération silencieuse sans effet.

See Also

PHP Features

Last updated: 11 October 2026