我已经使用SplobjectStorage实现了一个简单的复合模式,如上所述:

class Node
{
    private $parent = null;

    public function setParent(Composite $parent)
    {
        $this->parent = $parent;
    }
}

class Composite extends Node
{
    private $children;

    public function __construct()
    {
        $this->children = new SplObjectStorage;
    }

    public function add(Node $node)
    {
        $this->children->attach($node);
        $node->setParent($this);
    }
}

每当我尝试序列化复合对象时,PHP 5.3.2都会抛出我 Segmentation Fault。仅当我向对象添加任何类型的任何类型的节点时,才会发生这种情况。

这是有问题的代码:

$node = new Node;
$composite = new Composite;
$composite->add($node);
echo serialize($composite);

虽然这是有效的:

$node = new Node;
$composite = new Composite;
echo serialize($composite);

另外,如果我用array()而不是splobjectStorage实现复合模式,则所有运行也不错。

我做错了什么?

有帮助吗?

解决方案

通过设置父,您有一个圆形参考。 PHP将尝试序列化复合材料,所有节点,而节点依次将尝试序列化复合材料。

你可以使用魔术 __sleep__wakeup() 序列化时删除父母参考的方法。

编辑:

看看是否将它们添加到 Composite 解决了问题:

public function __sleep()
{
    $this->children = iterator_to_array($this->children);
    return array('parent', 'children');
}
public function __wakeup()
{
    $storage = new SplObjectStorage;
    array_map(array($storage, 'attach'), $this->children);
    $this->children = $storage;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top