Bart van Heukelom
Bart van Heukelom

Reputation: 44104

PHP remove object reference before serialize, restore after

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();

Upvotes: 2

Views: 3036

Answers (3)

anyaelena
anyaelena

Reputation: 108

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

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

Upvotes: 4

Gordon
Gordon

Reputation: 317049

Yes. Have a look at __sleep and __wakeup

Upvotes: 1

Related Questions