cookie类封装
<?php /** * cookie的设置,读取,更新,删除 */ class CustomCookie{ static private $_instance=null; private $expire = 0; //默认会话cookie private $path = ''; private $domain = ''; private $secure=false; private $httponly=false; /** * 构造函数完成cookie参数初始化工作 * @param array $options [cookie相关选项] */ private function __construct(array $options){ $this->setOptions($options); } /** * 设置相关选项 * @param array $options [cookie选项] */ private function setOptions(array $options){ if(isset($option['expire'])){ $this->expire=(int)$options['expire']; } if(isset($option['path'])){ $this->path=(int)$options['path']; } if(isset($option['domain'])){ $this->domain=(int)$options['domain']; } if(isset($option['secure'])){ $this->secure=(int)$options['secure']; } if(isset($option['httponly'])){ $this->httponly=(int)$options['httponly']; } return $this; } /** * 单例模式 * @param array $options [cookie相关选项] * @return [object] [对象实例] */ public static function getInstance(array $options){ if(is_null(self::$_instance)){ $class=__CLASS__; self::$_instance = new $class($options); } return self::$_instance; } /** * 设置cookie * @param [type] $name [description] * @param [type] $value [description] * @param array $options [description] */ public function set($name,$value, $options=array()){ if(is_array($options)&&count($options)>0){ $this->setOptions($options); } if(is_array($value) || is_object($value)){ $value = json_encode($value,JSON_FORCE_OBJECT); } if($options['expire']){ $expire = $options['expire']; }else{ $expire = $this->expire; } setcookie($name,$value,$expire,$this->path,$this->domain,$this->secure,$this->httponly); } /** * 得到指定的cookie * @param [type] $name [description] * @return [mixed] [返回null或者对象或者标量类型] */ public function get($name){ if(isset($_COOKIE[$name])){ return substr($_COOKIE[$name],0,1)=='{'?json_decode($_COOKIE[$name]) : $_COOKIE[$name]; }else{ return null; } } /** *删除cookie */ public function delete($name,$options=array()){ if(is_array($options) && count($options)>0){ $this->setOptions($options); } if(isset($_COOKIE[$name])){ setcookie($name,'',time()-1,$this->path,$this->domain,$this->secure,$this->httponly); } } /** * 删除所有cookie */ public function deleteAll($options = array()){ if(is_array($options) && count($options)>0){ $this->setOptions($options); } if(!empty($_COOKIE)){ foreach($_COOKIE as $name=>$value){ setcookie($name,'',time()-1,$this->path,$this->domain,$this->secure,$this->httponly); unset($_COOKIE[$name]); } } } } $cookie = CustomCookie::getInstance(array()); // var_dump($cookie); // $cookie->set('aa',111,array()); // $cookie->set('bb',222,array()); // $cookie->set('cc',333,$options['expire']=time()+3600); $options=array( 'expire'=>time() + 3600, ); $cookie->set('cc',333,$options); var_dump($cookie->get('cc'));