我是一个AS3编码器,我做了一些PHP,我很难做一个可以缓存变量的静态类。PHP缓存类
这是我到目前为止有:
<?php
class Cache {
private static $obj;
public static function getInstance() {
if (is_null(self::$obj)){
$obj = new stdClass();
}
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public static function set($key,$value){
self::$obj->$key = $value;
}
public static function get($key){
return self::$obj->$key;
}
}
?>
我用的是下面我的变量设置成我的静态类的一个对象:
<?php
include 'cache.php';
$cache = new Cache();
$cache->set("foo", "bar");
?>
这是检索的变量
<?php
include 'cache.php';
$cache = new Cache();
$echo = $cache->get("foo");
echo $echo //doesn't echo anything
?>
我在做什么错?谢谢
这里你的问题是,你要建一个单身,但你**不能**实例化。当你设置'foo'时,你正在存储该特定实例的值。但是当你想要检索它时,你正在创建一个新的实例。 – mrlee 2012-02-09 23:24:07
@fuzzyDunlop,好的,我看到了,所以我去了$ cache = Cache :: getInstance(); $ cache-> set(“foo”,“bar”);设置和$ cache = Cache :: getInstance(); echo $ cache-> get(“foo”);仍然不起作用:( – Eric 2012-02-09 23:28:48
)在这段代码中,你的'get'和'set'方法是'static',所以在调用它们时你需要使用'::'而不是' - >'。 – mrlee 2012-02-09 23:41:02