php 序列化常量

发布于 2024-10-19 08:22:02 字数 115 浏览 2 评论 0原文

是否可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

無心 2024-10-26 08:22:02

const 不是对象属性,而是类常量。也就是说,它属于您的类而不是它的任何对象。这也是为什么使用 A::XXX 而不是 $this->XXX 引用类常量的原因。

因此,您无法使用对象序列化该 const,就像无法序列化任何静态变量一样。

但是,当您反序列化该对象时,您将获得该对象作为该类的实例,因此您可以仅使用类名引用该常量:

$class = get_class(unserialize($A_obj));
echo $class::XXX;

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;
变身佩奇 2024-10-26 08:22:02

当然,可以序列化包含 const 属性的类的实例。

但是 const 属性不会出现在序列化字符串中:不需要它,因为它是常量:当字符串被反序列化时,它将是一个实例你的类——因此,从类的定义中拥有该常量属性。

序列化类的实例:

class A {
   const XXX = 'aaa';
   function test() {
       echo A::XXX;
   }
}

$a = new A();
$str = serialize($a);
var_dump($str);

您将得到:

string 'O:1:"A":0:{}' (length=12)

序列化字符串中不存在常量。

反序列化作品:

$b = unserialize($str);
var_dump($b);

而且,如果您尝试在反序列化时获得的 $b 对象上调用方法:

$b->test();

该常量确实找到,因为它在您的类定义中,并且您将得到 :

aaa

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
油焖大侠 2024-10-26 08:22:02
<?php 
class A
{
   const XXX = 'aaa';

}
$a = new A();
$b=serialize($a);
$c=unserialize($b); // copy of the $a obj

但你可以通过这种方式访问​​ cont A::XXX;

<?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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文