views:

23

answers:

3

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();
+1  A: 

Note to self: check docs first

http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep

Bart van Heukelom
+1  A: 

Yes. Have a look at __sleep and __wakeup

Gordon
+1  A: 

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

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

anyaelena