PHP序列化与反序列化

2017-10-20  本文已影响0人  赖赖魔的自留地

1. serialize和unserialize函数

这两个是序列化和反序列化PHP中数据的常用函数。

class person {
    public $name;
    public $gender;

    public function say() {
        echo $this->name," is ",$this->gender;
    }
}

$student = new person();
$student->name = 'Tom';
$student->gender = 'male';
$student->say();

$str = serialize($student);
echo $str;
//O:6:"person":2:{s:4:"name";s:3:"Tom";s:6:"gender";s:4:"male";}

$student_str = array(
                    'name' => 'Tom',
                    'gender' => 'male',
                    );
echo serialize($student_str);
//a:2:{s:4:"name";s:3:"Tom";s:6:"gender";s:4:"male";}

//容易看出,对象和数组在内容上是相同的,他们的区别在于对象有一个指针,指向了他所属的类。

2. json_encode 和 json_decode

JSON格式是开放的、可移植的。其他语言也可以使用它,使用json_encode和json_decode格式输出要比serialize和unserialize格式快得多。

$a = array('a' => 'Apple' ,'b' => 'banana' , 'c' => 'Coconut');

$json = json_encode($a);
echo $json;

echo '<pre>';
echo '<br /><br />';
var_dump(json_decode($json));
echo '<br /><br />';
var_dump(json_decode($json, true));

--------------------------------------------------------------------
{"a":"Apple","b":"banana","c":"Coconut"}


object(stdClass)#1 (3) {
  ["a"]=>
  string(5) "Apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(7) "Coconut"
}


array(3) {
  ["a"]=>
  string(5) "Apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(7) "Coconut"
}

json_decode转换时不加参数默认输出的是对象,如果加上true之后就会输出数组。

3. var_export 和 eval

var_export 函数把变量作为一个字符串输出;eval把字符串当成PHP代码来执行,反序列化得到最初变量的内容。

$a = array('a' => 'Apple' ,'b' => 'banana' , 'c' => 'Coconut');

$s = var_export($a , true);
echo $s;

echo '<br /><br />';

eval('$my_var=' . $s . ';');

print_r($my_var);

------------------------------------------------------------
array ( 'a' => 'Apple', 'b' => 'banana', 'c' => 'Coconut', )

Array ( [a] => Apple [b] => banana [c] => Coconut )
上一篇 下一篇

猜你喜欢

热点阅读