[PHP] Serializing objects with protected members

php.internals

Francisco M. Marzoa Alonso

21 years ago
Hi, I'm trying to wrote my own serialization routines and I've found a previsible problem: protected members are not visible to my serialization routine. This is ok and it should be as is, but I've seen that PHP's serialize function have access to that members anyway, so the question is: Is there any kind of hack that I can use to access those variables from my own serialization routine? Thx. a lot in advance, P.S. I've sent this message before to php general list, but I think its a more "internal" issue.

Andrey Hristov

21 years ago
Hi, Francisco M. Marzoa Alonso wrote:
> Hi, > > I'm trying to wrote my own serialization routines and I've found a > previsible problem: protected members are not visible to my > serialization routine. This is ok and it should be as is, but I've seen > that PHP's serialize function have access to that members anyway, so the > question is: Is there any kind of hack that I can use to access those > variables from my own serialization routine? > > Thx. a lot in advance, > > P.S. I've sent this message before to php general list, but I think its > a more "internal" issue. >
Are you writing your routines in PHP or in C? C code can access protected variables easily since the Zend Engine exposes an API function to unmangle them (they are stored in the properties hash mangled - public properties are stored unmangled). Now I realize that it can be a problem for users having their session written in DB and writing their session handler in PHP since they cannot access private and protected member variables and they serialize by using serialize() over the session data passed to the write() routine. There is a hack to access private data of an object. <?php class f{ private $priv=1; protected $prot=2; public $pub=3; } $f=new f(); var_dump($b=array_keys((array)$f)); var_dump($f); } ?> array(3) { [0]=> string(7) "fpriv" [1]=> string(7) "*prot" [2]=> string(3) "pub" } object(f)#1 (3) { ["priv:private"]=> int(1) ["prot:protected"]=> int(2) ["pub"]=> int(3) } One can use either arrays to get access to hidden data. The second hash is easier to use. The elements in the first one are just like they are stored in the memory. Private and protected members have hash keys starting with \0 (ord(0)) If the second byte is * then it is a protected member, otherwise the name of the class where the private property was defined is next and after the name \0 comes again. If it is a protected member after the * there is also a \0 byte. To the end is the name of the property. HTH, Andrey

Francisco M. Marzoa Alonso

21 years ago
Thanks a lot, it was very useful. Andrey Hristov wrote: [...]
> There is a hack to access private data of an object.
[...]