- 序列化斟或,指將PHP中 對象奶陈、類、數(shù)組十饥、變量丧蘸、匿名函數(shù)等漂洋,轉(zhuǎn)化為字符串遥皂,用戶「數(shù)據(jù)庫存儲」力喷、「數(shù)據(jù)的傳輸」
- 反序列化,將字符串轉(zhuǎn)為:對象演训、類弟孟、數(shù)組、變量样悟、匿名函數(shù)
- 序列化在每個編程語言里面都存在拂募,比如MFC
- 廣義的說:將一個Word保存為docx,這就是序列化的過程窟她。打開docx文檔陈症,顯示內(nèi)容,就是反序列化的過程
- ini/json/XML也是序列化的一種
1. serialize和unserialize函數(shù)
這兩個是序列化和反序列化PHP中數(shù)據(jù)的常用函數(shù)震糖。
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";}
//容易看出录肯,對象和數(shù)組在內(nèi)容上是相同的,他們的區(qū)別在于對象有一個指針吊说,指向了他所屬的類论咏。
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轉(zhuǎn)換時不加參數(shù)默認輸出的是對象,如果加上true之后就會輸出數(shù)組雅宾。
3. var_export 和 eval
var_export 函數(shù)把變量作為一個字符串輸出养涮;eval把字符串當成PHP代碼來執(zhí)行,反序列化得到最初變量的內(nèi)容。
$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 )