Is it possible to run a method of a class in a separate thread in PHP?
for example:
Thread:
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 a method callThread, error:
$obj = new MyClass();
$obj->callThread();
Serialization of 'Closure' is not allowed
Or what else there are ways to start a thread, so that the flow had access to the methods of the object class MyClass?
I think what you are looking for is pthreads, from PHP DOC:
pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.
A Threaded Object: A Threaded Object forms the basis of the functionality that allows pthreads to operate. It exposes synchronization methods and some useful interfaces for the programmer.
And here it is on GitHub - PHTREADS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With