1 <?php
2 class File{
3 //$key 相当于缓存文件的文件名
4 //$value 缓存数据
5 private $_dir;//定义默认路径
6 const EXT='.txt';
7 public function __construct(){
8 $this->_dir=dirname(__FILE__).'/files/';
9 }
10 public function cacheData($key,$value="",$path=""){
11 $filename=$this->_dir .$path .$key .self::EXT;
12 if($value!==""){//将$value值写入缓存
13 if(is_null($value)){
14 return @unlink($filename);//删除缓存,@屏蔽错误信息的输出的作用
15 }
16 $dir=dirname($filename);
17 if(!is_dir($dir)){
18 mkdir($dir,0777);
19 }
20 return file_put_contents($filename,json_encode($value));
21 }
22 //获取缓存
23 if(!is_file($filename)){
24 return false;
25 }else{
26 return json_decode(file_get_contents($filename),true);
27 }
28 }
29 }
30 ?>
<?php
require_once("file.php");
$data=array(
'id'=>1,
'name'=>'新浪',
'type'=>array(4,5,6),
'test'=>array(1,45,67=>array(123,'tsysa'),),
);
$file=new File();
//index_mk_cache 为缓存文件名
//$data 为缓存数据
if($file->cacheData('index_mk_cache',$data)){//当$data换为null时,实现输出缓存文件的效果
echo "success";
}else{
echo"error";
}
?>