2012-02-09 89 views
0

我是一个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 
?> 

我在做什么错?谢谢

+0

这里你的问题是,你要建一个单身,但你**不能**实例化。当你设置'foo'时,你正在存储该特定实例的值。但是当你想要检索它时,你正在创建一个新的实例。 – mrlee 2012-02-09 23:24:07

+0

@fuzzyDunlop,好的,我看到了,所以我去了$ cache = Cache :: getInstance(); $ cache-> set(“foo”,“bar”);设置和$ cache = Cache :: getInstance(); echo $ cache-> get(“foo”);仍然不起作用:( – Eric 2012-02-09 23:28:48

+0

)在这段代码中,你的'get'和'set'方法是'static',所以在调用它们时你需要使用'::'而不是' - >'。 – mrlee 2012-02-09 23:41:02

回答

0

我已经适应上述@ prodigitalson的代码来获得一些初步的作品(并具有很大的提升空间):

class VarCache { 
    protected static $instance; 
    protected static $data = array(); 

    protected function __construct() {} 

    public static function getInstance() { 
    if(!self::$instance) { 
     self:$instance = new self(); 
    } 

    return self::$instance; 
    } 

    public function get($key) { 
    self::getInstance(); 

    return isset(self::$data[$key]) ? self::$data[$key] : null; 
    } 

    public function set($key, $value) { 
    self::getInstance(); 
    self::$data[$key] = $value; 
    } 
} 

使用

VarCache::set('foo', 'bar'); 
echo VarCache::get('foo'); 
// 'bar' 

你会希望这个类是可用的在任何你需要的地方,如果你想要它坚持在请求之间,我会考虑使用Memcached或类似的东西,这会给你你需要的一切。

你可以选择使用一些SPL功能,如ArrayObject,如果你想聪明:)

+0

确实有效,谢谢。我会检查Memcached :) – Eric 2012-02-09 23:37:21

+0

事实上,Memcache(没有D - 我在WAMP上)是我真正需要的。我只是安装它,它的规则。对于像WAMP这样想要安装它的人,请查看:http://shikii.net/blog/installing-memcached-for-php-5-3-on-windows-7/ – Eric 2012-02-10 00:27:45

1

试试这个:

class VarCache { 
    protected $instance; 
    protected $data = array(); 
    protected __construct() {} 

    public static function getInstance() 
    { 
    if(!self::$instance) { 
     self:$instance = new self(); 
    } 

    return self::$instance; 
    } 

    public function __get($key) { 
    return isset($this->data[$key]) ? $this->data[$key] : null; 
    } 

    public function __set($key, $value) { 
    $this->data[$key] = $value; 
    } 
} 

// usage 

VarCache::getInstance()->theKey = 'somevalue'; 
echo VarCache::getInstance()->theKey; 
+0

嗯没有复制粘贴这个确切的代码,并没有回应任何东西.. – Eric 2012-02-09 23:22:00