在PHP中的函数之间共享变量,而无需使用全局变量 [英] Share variables between functions in PHP without using globals
问题描述
我有一个用于与Memcache服务器进行交互的类.我具有用于插入,删除和检索数据的不同功能.最初,每个函数都调用memcache_connect()
,但这是不必要的,例如:
I have a class for interacting with a memcache server. I have different functions for inserting, deleting and retrieving data. Originally each function made a call to memcache_connect()
, however that was unnecessary, e.g.:
mc->insert()
mc->get()
mc->delete()
将建立三个内存缓存连接.我通过为该类创建构造来解决此问题:
would make three memcache connections. I worked around this by creating a construct for the class:
function __construct() {
$this->mem = memcache_connect( ... );
}
,然后在需要资源的任何地方使用$this->mem
,因此三个功能中的每一个都使用相同的memcache_connect
资源.
and then using $this->mem
wherever the resource was needed, so each of the three functions use the same memcache_connect
resource.
没关系,但是如果我在其他类中调用该类,例如:
This is alright, however if I call the class inside other classes, e.g.:
class abc
{
function __construct() {
$this->mc = new cache_class;
}
}
class def
{
function __construct() {
$this->mc = new cache_class;
}
}
然后,它只需要 一个时,仍会打两个memcache_connect
呼叫.
then it is still making two memcache_connect
calls, when it only needs one.
我可以对全局变量执行此操作,但是如果不需要,我不希望使用它们.
I can do this with globals but I would prefer not to use them if I don't have to.
示例全局实现:
$resource = memcache_connect( ... );
class cache_class
{
function insert() {
global $resource;
memcache_set( $resource , ... );
}
function get() {
global $resource;
return memcache_get( $resource , ... );
}
}
然后,无论该类被调用多少次,都只会对memcache_connect
进行一次调用.
Then no matter how many times the class is called there will only be one call to memcache_connect
.
有没有办法做到这一点,还是应该只使用全局变量?
Is there a way to do this or should I just use globals?
推荐答案
我将使用单例模式编写另一个类的代码,以获取唯一的内存缓存实例.像这样-
I would code another class using singleton pattern for getting the only instance of memcache. Like this -
class MemCache
{
private static $instance = false;
private function __construct() {}
public static function getInstance()
{
if(self::$instance === false)
{
self::$instance = memcache_connect();
}
return self::$instance;
}
}
和用法-
$mc = MemCache::getInstance();
memcache_get($mc, ...)
...
这篇关于在PHP中的函数之间共享变量,而无需使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!