开发者

Does PHP serialize Object Methods?

开发者 https://www.devze.com 2023-03-17 07:23 出处:网络
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).

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 开发者_JAVA技巧in the manual shows a method being serialised, then unserialised and used.

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


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.


The method is not serialized, but the class of which the object is a member is:

The methods in an object will not be saved, only the name of the class.

Therefore when you unserialize, you obtain an instance of the same class, so you can invoke the method on that unserialized instance, as the method is part of the class definition rather than a member of the object itself. This of course assumes you have the exact same class definition at the time of unserialization:

In order to be able to unserialize() an object, the class of that object needs to be defined.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号