Memcache:在非对象上调用成员函数get()

时间:2012-05-27 19:11:21

标签: php object memcached

我在this steps

之后的CentOS中安装了memcached

这是PHP错误:

Fatal error: Call to a member function get() on a non-object in /home/piscolab/public_html/keepyourlinks.com/includes/funciones.php on line 22

代码:

/* MEMCACHE */
$memcache = new Memcache();
$memcache->pconnect('localhost',11211);

/* checks in memcache, if not: query and save to memcache */
function cache_query($sql,$nombre,$tiempo = -1){
    if($tiempo == -1) $tiempo = time() + 24*60*60*365;
    $consulta = $memcache->get($nombre);  /* THIS is the line */
    if ( $consulta === false) {
        $consulta = mysql_query($sql);
        $memcache->set($nombre,$consulta,0,$tiempo);
        $_SESSION['tQ']++;
    }else $_SESSION['tQC']++;
    return $consulta;
}

我这样称呼函数:

$result = cache_query('select * from users','all_users');

我错过了什么?

2 个答案:

答案 0 :(得分:2)

此处$memcache对象为out of scope

将以下行添加到您的函数顶部:

global $memcache;

或将其作为参数传递:

function cache_query($sql, $nombre, $memcache, $tiempo = -1) {
    ...
}
$result = cache_query('select * from users','all_users', $memcache);

答案 1 :(得分:0)

你需要这样做:

global $memcache;

在你的功能中。

有关变量范围的信息,请参阅此处:

http://php.net/manual/en/language.variables.scope.php