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条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大