描述:
创建了一个扩展Thread的php类ChildThread。它看起来像这样:
use Thread;
class ChildThread extends Thread
{
public $data;
private $anonymous_func;
public function __construct($anonymous_func)
{
$this->anonymous_func = $anonymous_func;
}
public function run(){
$func = $this->anonymous_func;
$this->data = $func();
}
}
问题:
我得到以下错误:
尝试从全局命名空间加载类"Thread"。你是不是忘记"使用"语句了吗?
我显然有一个use
语句,它使用了正确的类:
/**
* When the start method of a Thread is invoked, the run method code will
* be executed in separate Thread, asynchronously.<br/>After the run method
* is executed the Thread will exit immediately, it will be joined with
* the creating Thread at the approriate time.
* @link http://www.php.net/manual/en/class.thread.php
*/
class Thread extends Threaded implements Traversable, Countable, ArrayAccess {
/** class code here **/
}
问题:
为什么它说我需要一个"使用"语句,而我已经在使用它了?
您必须安装pthreads扩展,它提供了这些类。默认情况下,它不会安装在PHP Core中,因为它需要PHP的线程安全版本。事实上,PHP在标准发行版中并没有线程安全版本。
您可以通过获取PHP的源代码,并使用特殊的标志对其进行编译,从而启用ZTS的PHP(Zend Thread Safety(。对于Windows,也可以直接下载。
我建议您为web应用程序(不能使用线程(使用普通版本的PHP,为CLI应用程序(守护进程等(使用手工编译的ZTS版本。
一旦你有了ZTS版本的PHP,你就可以通过PECL安装pthreads,或者手动安装(这比正确编译PHP容易得多;(。