is it possible to serialize object like this , with const property?
开发者_运维问答class A
{
const XXX = 'aaa';
}
i guess no, but what is solution?
A const
is not an object property, it's a class constant. That is, it pertains to your class and not any of its objects. It's also why you refer to class constants using A::XXX
rather than $this->XXX
.
Therefore you can't serialize that const
with your objects, just like you can't serialize any static variables.
However, when you unserialize the object you will obtain it as an instance of that class, so you can just refer to the constant using the class name:
$class = get_class(unserialize($A_obj));
echo $class::XXX;
It is possible to serialize and instance of a class that contains a const
property, of course.
But that const
property will not be present in the serialized string : no need for it, as it's constant : when the string will be unserialized, it'll be an instance of your class -- and, so, have that constant property, from the class' definition.
Serializing an instance of your class :
class A {
const XXX = 'aaa';
function test() {
echo A::XXX;
}
}
$a = new A();
$str = serialize($a);
var_dump($str);
You'll get :
string 'O:1:"A":0:{}' (length=12)
The constant is not present in the serialized string.
De-serializing works :
$b = unserialize($str);
var_dump($b);
And, if you try calling a method on that $b
object, obtained whe unserializing :
$b->test();
The constant is indeed found, as it's in your class' definition, and you'll get :
aaa
<?php
class A
{
const XXX = 'aaa';
}
$a = new A();
$b=serialize($a);
$c=unserialize($b); // copy of the $a obj
but you can access cont by this way A::XXX;
精彩评论