美文网首页
PHP序列化与反序列化

PHP序列化与反序列化

作者: 赖赖魔的自留地 | 来源:发表于2017-10-20 17:31 被阅读0次
  • 序列化,指将PHP中 对象、类、数组、变量、匿名函数等,转化为字符串,用户「数据库存储」、「数据的传输」
  • 反序列化,将字符串转为:对象、类、数组、变量、匿名函数
  • 序列化在每个编程语言里面都存在,比如MFC
  • 广义的说:将一个Word保存为docx,这就是序列化的过程。打开docx文档,显示内容,就是反序列化的过程
  • ini/json/XML也是序列化的一种

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 )

相关文章

网友评论

      本文标题:PHP序列化与反序列化

      本文链接:https://www.haomeiwen.com/subject/shnmuxtx.html