php的序列化和反序列化
-
serializa()序列化,就是将本来不能直接存储的数据转换成可以存储的数据,并且不会丢失数据。序列化后的PHP数据为字符串。
-
unserialia()反序列化,就是将序列化后的数据,还原为原来的数据。
function cache(string $name, array $data=null){ //DIRECTORY_SEPARATOR这个系统常量是用来显示系统分隔符的 $file = 'cache'.DIRECTORY_SEPARATOR.md5($name).'.php'; if (is_null($data)) { # is_file()这个方法是用来判断,文件名是否为一个正常文件,他会传入一个文件路径,如果文件存在则为true否则为false $content = is_file($file)?file_get_contents($file):null; return unserialize($content)?:null; } else { # 将一个字符串写入文件,传入俩个参数,文件地址、数据。它会依次的执行了打开、写、关闭 return file_put_contents($file,serialize($data)); } } $config = include "database.php"; cache('database',$config); -
序列化后的格式
#布尔类型 b:value b:0 #false b:1 #true #整数型 i:value i:1 i:-1 #字符型 s:length:"value"; s:4:"aaaa"; #NULL型: N; #数组: a:<length>:{key; value pairs}; a:1:{i:1;s:1:"a";} #对象: O:<class_name_length>:"<class_name>":<number_of_properties>:{<properties>}; O:6:"person":3:{s:4:"name";N;s:3:"age";i:19;s:3:"sex";N;}目前认知总结:
序列化就是把php的数据转换为有序列可存储的数据
每日进步一点点