Question

I have some objects that I wish to cache on disk. I use serialize() in this process. The objects contain some references to other objects. I don't want those to be serialized as well (that is done in some other place) because it would give me duplicate instances of the same real-world object when unserializing.

Is there a way to change the object references to strings (referring to the same objects, but by ID) before serializing and changing them back after, and to do this inside the class code (not before and after the (un)serialize statements)?

Good:

class TheStuff {
 private $otherThing;
 private function __yeahDudeDoThisOnSerialize() {
  $this->otherThing = $this->otherThing->name;
 }
 private function __viceVersa() {
  $this->otherThing = get_thing_by_name($this->otherThing);
 }
}

serialize($someStuff);

Bad:

class TheStuff {
 private $otherThing;
 public function yeahDudeDoThisOnSerialize() {
  $this->otherThing = $this->otherThing->name;
 }
 public function viceVersa() {
  $this->otherThing = get_thing_by_name($this->otherThing);
 }
}

$someStuff->yeahDudeDoThisOnSerialize();
serialize($someStuff);
$someStuff->viceVersa();
Was it helpful?

Solution

I think you are looking for __sleep() and __wakeup().

http://php.net/manual/en/language.oop5.magic.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top