Back to results for “Closures”
PHP › Asynchronous PHP (ReactPHP & Swoole)

What is ReactPHP and how does its event loop enable non blocking, asynchronous behavior in standard PHP?

Beginner

Answer

ReactPHP is a library that provides an event driven, non blocking input and output model for PHP, built around a central event loop that continuously checks for completed operations, such as a finished network request, and calls the appropriate callback function when that operation completes, letting a single PHP process handle many operations concurrently without needing to wait idly for each one to finish before starting the next.
$loop = React\EventLoop\Loop::get();
$loop->addTimer(2, function () {
    echo "Two seconds have passed\n";
});
$loop->run();
Real-world example A real time notification server built with ReactPHP handles thousands of open client connections simultaneously within a single process, using the event loop to efficiently respond to each client only when there is actually new data to send.

Common follow-ups: What is a callback function and how does it relate to the event loop?;How does ReactPHP compare to using traditional PHP-FPM for web requests?