【问题标题】:Memcache: Call to a member function get() on a non-objectMemcache:在非对象上调用成员函数 get()
【发布时间】:2012-05-28 04:24:55
【问题描述】:

我按照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');

我错过了什么?

【问题讨论】:

    标签: php object memcached


    【解决方案1】:

    $memcache 对象在这里是out of scope

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

    global $memcache;
    

    或者作为参数传递:

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

    【讨论】:

    • 谢谢!我确实添加了全局,现在 php 没有记录任何错误或打印任何 HTML 代码,知道吗?
    • 这可能是因为现在$memcache->get() 之后的行正在运行,因为它不再抛出致命错误 - 这些行中一定有错误。
    • 因为仅仅让一个对象全局不能导致这样的问题:)
    • 不要那样做,为此打开一个新问题
    【解决方案2】:

    你需要做的:

    global $memcache;
    

    在你的函数中。

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

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

    【讨论】:

    • 好吧,如果我写: global $m = new memcache(); /* 或 memcached */ 脚本失败(如果我删除该行,则脚本有效)
    • 你不应该这样做global $var = something;。您在函数内部使用global $varname; 来访问在函数外部声明的变量,否则该变量超出范围。你接受了另一个答案,它说了同样的话,所以你原来的问题一切都很好,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2010-09-26
    • 2012-04-20
    • 2015-05-01
    相关资源
    最近更新 更多