views:

64

answers:

1

In my task would be very nice to write a kind of objects serialization (for XML output). I've already done it, but have no idea, how to avoid recursive links.

The trouble is that some objects must have public(!) properties with links to their parents (it's really nessecary). And when I try to serialize a parent object which agregates some children - children with links to parent do recursion forever.

Is there a solution to handle such recursions as print_r() does without hacks? I can't use somthing like "if ($prop === 'parent')", because sometimes there's more than 1 link to parents from different contexts.

+1  A: 

Write your own serialization function and always pass it a list of already-processed items. Since PHP5 (I assume, you are using php5) always copies references to an object, you can do the following:

public function __sleep() {
    return $this->serialize();
}
protected function serialize($processed = array()) {
    if (($position = array_search($this, $processed, true)) !== false) {
        # This object has already been processed, you can use the
        # $position of this object in the $processed array to reference it.
        return;
    }
    $processed[] = $this;
    # do your actual serialization here
    # ...
}
soulmerge
Not to be a nitpicker, but that should of course be: return $this->serialize();
n3rd
Shame upon me... a list of already used instances is pretty nice solution! I can do it even from outside, and there's no need to supply every class with serialization method.Thanks a lot for a great answer.PS: btw, yes php5 of course. In php4 questions about OOP are one level more dirty IMHO.
Jet
@n3rd: thx, fixed
soulmerge