duanla1996 2014-08-04 15:57
浏览 54
已采纳

是否有可能在php中序列化SplEnum

Is it possible serialize SplEnum? I'm trying use SplEnum, but userialized instance has only default value. For example:

class Test extends SplEnum
{
    const __default = self::A;
    const A = 1;
    const B = 2;
}

...

$t = new Test( Test::B );
$s = serialize($t);
$t2 = unserialize($s);

Variable $t2 is instance of Test but with default value.

  • 写回答

2条回答 默认 最新

  • dongyi9484 2014-08-04 17:46
    关注

    The reason why you don't get an expected value after unserialize is that SplEnum is not just a regualar PHP class. It is a kind of hack. The value is kept in its own structure, not in PHP object itself as you can see here

    https://github.com/davidcoallier/SPL_Types/blob/master/spl_type.c in method spl_type_object_new_ex

    They create an internal structure "object"

    object = emalloc(sizeof(spl_type_object));
    

    that holds the value

    ZVAL_ZVAL(object->value, *def, 1, 0);
    

    The unserialize function does not know a thing about this internal object and cannot change its value. Hence this peculiar behaviour.

    Update

    You might want to use casting in order to preserve the object's value. In your case it could have been:

    $casted_value = (int) $t;
    

    At least an integer is easier to handle.

    Update 2

    A working example with working serialization.

    class Test2 extends SplEnum  implements Serializable 
    {
        const __default = 1;
        const A = 1;
        const B = 27;
        const C = 31;
    
        public function serialize() {
                return serialize ((int) $this);
        }
    
        public function unserialize($serialized) {
            $this->__construct (unserialize($serialized));
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系