1

我遇到了一个问题,我想将一个 SplHeap(或任何其他类型的类似 Spl 堆的对象,例如 SplPriorityQueue、SplMinHeap、SplMaxHeap)存储到我的 Memcached 的位置以便以后使用它们。

我注意到在没有序列化的情况下这样做会导致丢失存储在堆中的数据。

对这个问题有什么建议吗?或者如何序列化 PHP SplHeap?

谢谢

4

1 回答 1

1

The SPL comes with a Serializable Interface. So your SplHeap class should implement this interface like the following code.

class MySplHeap extends SplMinHeap implements Serializable {

    public function compare(ArrayObject $a, ArrayObject $b) {
        return ($b->member - $a->member);
    }

    public function serialize() {
        $objects = new ArrayObject();
        $heap = clone $this;

        foreach ($heap as $node) {
            $objects[] = $node;
        }

        return serialize($objects);
    }

    public function unserialize($serializedData) {
        if (!is_object($serializedData) && gettype($serializedData) == 'object') {
            $serializedData = serialize($serializedData);
        }

        $objects = unserialize($serializedData);

        foreach ($objects as $node) {
            $this->insert($node);
        }
    }

}

The Serializable interface implements the serialize() and unserialize() methods. So you can declare special functionality in your splheap class.

于 2013-03-27T10:59:27.463 回答