douche1936 2013-08-27 08:35
浏览 36
已采纳

在线程中存储闭包失败

I'm trying to use a closure as a callback once a thread is done running. However I'm running into what seems to be a limit/failure of PHP or the pthread extension.

My dev stack is running on Win7 x64 with PHP 5.5.3 x86 TS, pthread version 0.44.

The following code works :

class Test
{
    public $callbackVar;
}

$test = new Test();

$callbackVar = function()
{
    echo "Callback var invoked.";
};

$test->callbackVar = $callbackVar;
$test->callbackVar->__invoke();

But as soon as I derive Test from Thread, running the script gives an error :

class Test extends Thread
{
    public $callbackVar;
    public function run() { }
}

$test = new Test();

$callbackVar = function()
{
    echo "Callback var invoked.";
};

$test->callbackVar = $callbackVar;
// assert() returns true
assert($test->callbackVar === null);
$test->callbackVar->__invoke();   

With the following output

Fatal error: Call to a member function __invoke() on a non-object

Anyone ever had this issue ? Any possible workaround ? I'd rather not use eval if possible... I've tried many workarounds, such as rewrapping into another closure, using a ReflectionFunction, ... nothing cuts it.

  • 写回答

1条回答 默认 最新

  • doukui2011 2013-08-27 18:48
    关注

    Zend does not allow you to serialize closure objects.

    So it's not something you should try to work around, possibly at some time in the future Zend will allow serialization of Closures, pthreads will not require changes at that time.

    You'll just have to do it the old fashioned way ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵