php 序列化常量
是否可以使用 const 属性序列化这样的对象?
class A
{
const XXX = 'aaa';
}
我想不是,但是解决方案是什么?
is it possible to serialize object like this , with const property?
class A
{
const XXX = 'aaa';
}
i guess no, but what is solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
const
不是对象属性,而是类常量。也就是说,它属于您的类而不是它的任何对象。这也是为什么使用A::XXX
而不是$this->XXX
引用类常量的原因。因此,您无法使用对象序列化该 const,就像无法序列化任何静态变量一样。
但是,当您反序列化该对象时,您将获得该对象作为该类的实例,因此您可以仅使用类名引用该常量:
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 usingA::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:
当然,可以序列化包含 const 属性的类的实例。
但是 const 属性不会出现在序列化字符串中:不需要它,因为它是常量:当字符串被反序列化时,它将是一个实例你的类——因此,从类的定义中拥有该常量属性。
序列化类的实例:
您将得到:
序列化字符串中不存在常量。
反序列化作品:
而且,如果您尝试在反序列化时获得的
$b
对象上调用方法:该常量确实找到,因为它在您的类定义中,并且您将得到 :
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 :
You'll get :
The constant is not present in the serialized string.
De-serializing works :
And, if you try calling a method on that
$b
object, obtained whe unserializing :The constant is indeed found, as it's in your class' definition, and you'll get :
但你可以通过这种方式访问 cont
A::XXX;
but you can access cont by this way
A::XXX;