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'));
本文介绍了一种使用PHP原生序列化和反序列化功能自建缓存的方法。通过在同级目录下创建名为cache的文件夹,利用md5算法生成唯一文件名,实现数据的存储与读取。代码示例展示了如何存取数据并检查缓存状态。

被折叠的 条评论
为什么被折叠?



