PHP: run a class method on a separate thread
Is it possible to run a class method on a separate thread in PHP?
for example:
Subject:
class AsyncThread extends \Thread {
private $method;
private $obj;
private $params;
private $timeout;
public function __construct($obj, $method, $params, $timeout){
$this->obj = $obj;
$this->method = $method;
$this->params = $params;
$this->timeout = $timeout;
}
public function run() {
sleep($this->timeout);
if (call_user_func_array([$this->obj, $this->method], $this->params)) {
return true;
} else return false;
}
}
Class:
class MyClass {
private $param = 'username';
public function callThread() {
$thread = new AsyncThread($this, 'threadMethod', ['hello'], 5);
}
public function threadMethod($param) {
echo "{$param} {$this->param}";
}
}
When I try to call the callThread method, the error is:
$obj = new MyClass();
$obj->callThread();
Serialization of 'Closure' is not allowed
Or what else are there ways to start a thread so that the thread has access to the methods of the MyClass object class?
source to share
I think you are looking for pthreads , from the PHP DOC:
pthreads is an object oriented API that allows the user to multithread in PHP. It includes all the tools you need to create multi-threaded applications that target the web or console. PHP applications can create, read, write, execute and synchronize with Themes, Workers and Threaded objects.
A Threaded Object: Threaded Object forms the basis of the functionality that allows pthreads to work. It covers synchronization techniques and some useful interfaces for the programmer.
And here it is on GitHub - PHTREADS
source to share