PHP原生利用序列化和反序列化自建一个缓存
直接上代码:
*注意: 使用本代码之前需在代码的同级目录下创建一个名为cache 的文件夹
<?php
//序列化与反序列化
function cache($name,$data = null){
//定义一个文件名
$file = 'cache' . DIRECTORY_SEPARATOR . md5($name) . '.cache';
if(is_null($data)){
//取数据
$data = is_file($file) ? file_get_contents($file) : null;
return unserialize($data);
}else{
//存数据
return file_put_contents($file,serialize($data)) ? '缓存成功!' : '缓存失败';
}
}
$data = include '11.php';
print_r(cache('array'));