当前位置:Gxlcms > PHP教程 > phpmemcache单例

phpmemcache单例

时间:2021-07-01 10:21:17 帮助过:20人阅读

  1. 先将__construct()设置为 private 这样就不允许在外部 new 了
  2. 在类的内部实例化一个对象。外部可以得到就行
classMemextendsMemcache{privatestatic$mem_instance = null;
    privatefunction__construct(){parent::__construct();
    }
    privatefunction__clone(){}
    publicstaticfunctionget_mem_ins(){if(null === self::$mem_instance){
            self::$mem_instance = new Memcache;
        }
        returnself::$mem_instance;
    }
}
  1. memcache 操作
php
    //连接$mem=new Memcache;
    $mem->connect("db.nowamagic.net", 12000);
    //保存数据$mem->set('key1', 'This is first value', 0, 60);
    $val=$mem->get('key1');
    echo "Get key1 value: ".$val."
"
; //替换数据$mem->replace('key1', 'This is replace value', 0, 60); $val=$mem->get('key1'); echo "Get key1 value: ".$val."
"
; //保存数组$arr=array('aaa', 'bbb', 'ccc', 'ddd'); $mem->set('key2', $arr, 0, 60); $val2=$mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "
"
; //删除数据$mem->delete('key1'); $val=$mem->get('key1'); echo "Get key1 value: ".$val."
"
; //清除所有数据$mem->flush(); $val2=$mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "
"
; //关闭连接$mem->close(); ?>
  1. 输出
Get key1 value: This is first value
Get key1 value: This is replace value
Get key2 value: Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd )
Get key1 value:
Get key2 value:

版权声明:知识取之于民,用之于民!欢迎转载,转载请开头附上本文链接,不定期更新文章!

以上就介绍了php memcache单例,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行