Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

php - Memcache: Call to a member function get() on a non-object

I installed memcached in a CentOS following this steps

This is the PHP error:

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

Code:

/* 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;
}

I call the function so:

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

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The $memcache object is out of scope here.

Add the following line to the top of your function:

global $memcache;

Or pass it as a parameter:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...