PHP manual serialization problems

In my task it would be very nice to write object serialization (for XML output). I've already done this, but have no idea how to avoid recursive references.

The problem is that some objects must have public (!) Properties with references to their parents (this is really inconvenient). And when I try to serialize the parent object that aggregates some of the children - children with parent recursion references forever.

Is there a hacks-free solution for handling recursions like print_r ()? I cannot use somthing like "if ($ prop === 'parent')" because sometimes there are more than 1 parent references from different contexts.

0


a source to share


1 answer


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 object references, 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
    # ...
}

      

+1


a source







All Articles