我是一个AS3程序员,我做了一点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
?>我做错了什么?谢谢
发布于 2012-02-10 07:34:21
我已经修改了上面@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 :)
发布于 2012-02-10 07:17:06
试试这个:
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;https://stackoverflow.com/questions/9220335
复制相似问题