使用 SplObjectStorage 序列化对象树时出错
我使用 SplObjectStorage 实现了一个简单的 Composite 模式,如上面的示例:
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);
}
}
每当我尝试序列化 Composite 对象时,PHP 5.3.2 都会抛出分段错误
。 仅当我向对象添加任意数量的任意类型的节点时,才会发生这种情况。
这是有问题的代码:
$node = new Node;
$composite = new Composite;
$composite->add($node);
echo serialize($composite);
虽然这个有效:
$node = new Node;
$composite = new Composite;
echo serialize($composite);
另外,如果我用 array() 而不是 SplObjectStorage 实现复合模式,所有运行也正常。
我做错了什么?
I have implemented a simple Composite pattern using SplObjectStorage, like the example above:
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);
}
}
Whenever I try to serialize a Composite object, PHP 5.3.2 throws me a Segmentation Fault
.
This only happens when I add any number of nodes of any type to the object.
This is the offending code:
$node = new Node;
$composite = new Composite;
$composite->add($node);
echo serialize($composite);
Although this one works:
$node = new Node;
$composite = new Composite;
echo serialize($composite);
Also, if I implement the Composite pattern with array() instead of SplObjectStorage, all runs ok too.
What I'm making wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过设置Parent,您就拥有了循环引用。 PHP 将尝试序列化复合体,它的所有节点以及节点将依次尝试序列化复合体..繁荣!
您可以使用魔法
__sleep
和__wakeup()
方法在序列化时删除(或对其执行任何操作)父引用。编辑:
看看将这些添加到
Composite
是否可以解决问题:By setting the Parent, you have a circular reference. PHP will try to serialize the composite, all of it's nodes and the nodes in turn will try to serialize the composite.. boom!
You can use the magic
__sleep
and__wakeup()
methods to remove (or do whatever to the) the parent reference when serializing.EDIT:
See if adding these to
Composite
fixes the issue: