doupingpeng7567 2012-03-22 10:40
浏览 129
已采纳

从PHP中的另一个函数中调用函数,但是在不在对象上下文中时使用$ this得到错误

I have the code below: from the getData function im trying to call get_xml within the same class, but I get the error Using $this when not in object context . I have been programming quite some time, so maybe my brains shut off, but imho this should work right? What am I missing here?

class modDataHelper {

    function getData($rid) {
        $xml = $this->get_xml('http://www.dataserver.nl/rss/feed.php?id=' . $rid, 60000);

        return $xml;
    }

    function get_xml($url, $max_age) {
        $file = 'cache/' . md5($url);

        if (file_exists($file)
                && filemtime($file) >= time() - $max_age) {
            // the cache file exists and is fresh enough
            return simplexml_load_file($file);
        }

        $xml = file_get_contents($url);
        file_put_contents($file, $xml);
        return simplexml_load_string($xml);
    }

}

In another file I call

$data = modDataHelper::getData(19464);
  • 写回答

3条回答 默认 最新

  • douzizang7783 2012-03-22 10:42
    关注

    You are calling a static method by using ::.

    There is no $this in static context use self.

    When to use self over $this?

    class modDataHelper {
    
        static function getData($rid) {
            $xml = self::get_xml('http://www.dataserver.nl/rss/feed.php?id=' . $rid, 60000);
    
            return $xml;
        }
    
        static function get_xml($url, $max_age) {
            $file = 'cache/' . md5($url);
    
            if (file_exists($file)
                    && filemtime($file) >= time() - $max_age) {
                // the cache file exists and is fresh enough
                return simplexml_load_file($file);
            }
    
            $xml = file_get_contents($url);
            file_put_contents($file, $xml);
            return simplexml_load_string($xml);
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现