Getting Started
suggest changeMulti-threading through this extension needs pthreads. It requires a ZTS (thread-safe) PHP build and is used from the CLI SAPI. The 3.x line targets PHP 7 and does not support PHP 8. Install it with
$ pecl install pthreads
and enable the extension in php.ini.
A simple example:
<?php
// NOTE: Code uses PHP7 semantics.
class MyThread extends Thread {
/**
* @var string
* Variable to contain the message to be displayed.
*/
private $message;
public function __construct(string $message) {
// Set the message value for this particular instance.
$this->message = $message;
}
// The work in this function runs on the other thread.
public function run() {
echo $this->message;
}
}
// Instantiate MyThread
$myThread = new MyThread("Hello from another thread!");
// Start the thread. Also it is always a good practice to join the thread explicitly.
// Thread::start() is used to initiate the thread,
$myThread->start();
// and Thread::join() causes the context to wait for the thread to finish executing
$myThread->join();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents