序列化和反序列化时阻止对象重写

时间:2016-04-20 04:58:46

标签: php serialization

我注意到在序列化一个简单的对象时我丢失了数组内容,并且我认为我会以某种方式重写数组。如何正确地构造代码,允许从最初启动的对象中保存数据?

<?php

class MyClass {

    private $array;

    function __construct($array) {
        $this->array = $array;
    }

    public function __sleep() {
        return $this->array;
    }
}

$array = array(
    'i1' => 1,
    'i2' => 2,
    'i3' => 3,
    'i4' => 4
);

$obj = new MyClass($array);
$ser = serialize($obj);
$des = unserialize($ser);

print_r($obj);
echo '<br><br>';
print_r($ser);
echo '<br><br>';
print_r($des);
?>

输出:

MyClass Object ( [array:MyClass:private] => Array ( [i1] => 1 [i2] => 2 [i3] => 3 [i4] => 4 ) )

O:7:"MyClass":4:{s:1:"1";N;s:1:"2";R:2;s:1:"3";R:2;s:1:"4";R:2;}

MyClass Object ( [array:MyClass:private] => [1] => [2] => [3] => [4] => ) 

2 个答案:

答案 0 :(得分:1)

尝试实施Serializable的{​​{1}}接口。

MyClass

答案 1 :(得分:1)

std::map::find我们可以找到解释如何使用

  

该函数在任何序列化之前运行。它可以清理   该对象应该返回一个名称的数组   应该序列化的那个对象的变量。

我必须返回它的名字,而不是只返回__sleep中的私有变量。

<?php

class MyClass {

    private $array;
    private $test;

    function __construct($array, $test) {
        $this->array = $array;
        $this->test = $test;
    }

    public function __sleep() {        
        return array('array', 'test');
    }
}

$test = 'test';
$array = array(
    'i1' => 1,
    'i2' => 2,
    'i3' => 3,
    'i4' => 4
);

$obj = new MyClass($array, $test);
$ser = serialize($obj);
$des = unserialize($ser);

print_r($obj);
echo '<br><br>';
print_r($ser);
echo '<br><br>';
print_r($des);

结果:

MyClass Object ( [array:MyClass:private] => Array ( [i1] => 1 [i2] => 2 [i3] => 3 [i4] => 4 ) [test:MyClass:private] => test )

O:7:"MyClass":2:{s:14:"MyClassarray";a:4:{s:2:"i1";i:1;s:2:"i2";i:2;s:2:"i3";i:3;s:2:"i4";i:4;}s:13:"MyClasstest";s:4:"test";}

MyClass Object ( [array:MyClass:private] => Array ( [i1] => 1 [i2] => 2 [i3] => 3 [i4] => 4 ) [test:MyClass:private] => test )