Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP serialize Object Methods?

The PHP reference manuals say that, when serializing an object, the methods will not be saved. (See http://www.php.net/manual/en/language.oop5.serialization.php, paragraph 1).

However, the first example given in the manual shows a method being serialised, then unserialised and used.

Isn't this a contradiction? Am I missing something?

like image 550
DatsunBing Avatar asked Dec 12 '22 11:12

DatsunBing


1 Answers

I must say, that I don't see where a method is serialized in the first example. When serializing no methods are serialized, only the classname and the properties. You can see this, if you have a look at the serialized data

$ser = serialize($object);
var_dump($ser);

You will notice, that there is no method mentioned. However, if you unserialize an object, its recreated by the classname. Or in other words: You will get a new object, but with the values you serialized before.

Usually this is not as important as it sounds like, because usually the serialized/unserialized object should behave the same.

// serialize 
class A {
  public $a = null;
  public function test () {
    echo "Hello";
  }
}
$a = new A;
echo $a->test(); // "Hello"
$x = serialize($a);

// unserialize (somewhere else)
class A {
  public $a = null;
  public function test () {
    echo "World";
  }
}
$a = unserialize($x);
echo $a->test(); // "World"

Here the serializer uses a "wrong" class and the output is different, than the expected one. As long as you make sure there are no classname collisions you usually don't need to think about it.

like image 65
KingCrunch Avatar answered Dec 31 '22 19:12

KingCrunch