SplPriorityQueue 序列化並反序列化後結果爲空問題解決

今天在嘗試把SplPriorityQueue對象序列化並反序列化後,遇到了問題。反序列化後在隊列裏的數據全沒了,這讓我很傷心。php

<?php
$pq = new SplPriorityQueue;
$pq->insert('imi 基於 Swoole 常駐內存協程開發框架', 100);
$pq->insert('https://gitee.com/yurunsoft/IMI', 200);
$pq->insert('https://github.com/Yurunsoft/IMI', 300);
var_dump($pq->count());

$serialize = serialize($pq);
var_dump($serialize);

$unserialize = unserialize($serialize);
var_dump($unserialize->count());

結果:git

int(3)
string(28) "O:16:"SplPriorityQueue":0:{}"
int(0)

莫得辦法,本身動手豐衣足食吧!經過自定義類繼承SplPriorityQueue並實現Serializable接口,來本身處理序列化和反序列化數據。github

解決問題的代碼以下:框架

class PriorityQueue extends \SplPriorityQueue implements \Serializable
{
    public function serialize()
    {
        return serialize(iterator_to_array(clone $this));
    }

    public function unserialize($serialized)
    {
        $array = unserialize($serialized);
        foreach($array as $p => $v)
        {
            $this->insert($v, $p);
        }
    }
}

$pq = new PriorityQueue;
$pq->insert('imi 基於 Swoole 常駐內存協程開發框架', 100);
$pq->insert('https://gitee.com/yurunsoft/IMI', 200);
$pq->insert('https://github.com/Yurunsoft/IMI', 300);
var_dump($pq->count());

$serialize = serialize($pq);
var_dump($serialize);

$unserialize = unserialize($serialize);
var_dump($unserialize->count());

結果:this

int(3)
string(180) "C:13:"PriorityQueue":153:{a:3:{i:2;s:32:"https://github.com/Yurunsoft/IMI";i:1;s:31:"https://gitee.com/yurunsoft/IMI";i:0;s:48:"imi 基於 Swoole 常駐內存協程開發框架";}}"
int(3)

完美解決~code

相關文章
相關標籤/搜索