在PHP中,是否可能在单独的线程中运行一个类的方法?
例如:
线程:
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 MyClass {
private $param = 'username';
public function callThread() {
$thread = new AsyncThread($this, 'threadMethod', ['hello'], 5);
}
public function threadMethod($param) {
echo "{$param} {$this->param}";
}
}
当我尝试调用一个名为callThread的方法时,出现错误:
$obj = new MyClass();
$obj->callThread();
Serialization of 'Closure' is not allowed
还有什么其他的方法可以启动线程,以便流程可以访问MyClass对象类的方法?