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


Calling a function from within another function in PHP, but get error Using $this when not in object context

我有下面的代码:在getData函数中,我试图在同一类中调用get_xml,但我得到了错误Using $this when not in object context。我已经编程很长一段时间了,所以也许我的大脑关闭了,但我觉得这应该行得通吗?我在这里错过了什么?

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);
    }
}

在另一个文件中,我称之为

$data = modDataHelper::getData(19464);

您正在使用::调用一个静态方法。

在静态上下文中没有$this使用self

什么时候使用超过$this的self?

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);
    }
}

您静态地调用getData,即没有对象实例,没有this。

你需要做一些类似的事情:

$data = new modDataHelper();
$data->getData(10464)

或者,如果你想使用静态方法,你需要将它们声明为"static",并使用"self::",而不是"$this->"。

有关更多信息,请参阅此处。

使用Ghommey的解决方案或。。。

$mdh = new modDataHelper;
$data = $mdh->getData(19464);

还可以看看这个

  • 属性或方法的可见性
  • 范围解析运算符(:)
  • 静态关键字