不在对象上下文中使用$this时出错


Error Using $this when not in object context

这里的第一篇文章,如果格式不正确,请提前道歉。我正在使用Instagram API来提取图像。Instagram API 一次只返回 1 页图像,但提供分页和next_url来抓取下一页图像。当我使用下面的函数fetchInstagramAPI时,只抓取第一页,php代码工作正常。

当我尝试将loopPages函数与fetchInstagramAPI函数一起使用时,尝试一次抓取所有页面时,我收到错误"不在对象上下文中使用$this"。知道吗?提前感谢您的帮助。

函数获取InstagramAPI获取我们的数据

<?php
  function fetchInstagramAPI($url){
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 20);
         $contents = curl_exec($ch);
         curl_close($ch); 
         return json_decode($contents);
    }

函数循环页面使用分页和next_url来抓取图像的所有页面

  function loopPages($url){
    $gotAllResults = false;
    $results = array();
    while(!$gotAllResults) {
    $result = $this->fetchInstagramAPI($url);
    $results[] = $result;
    if (!property_exists($result->pagination, 'next_url')) {
        $gotAllResults = true;
    } else {
        $url = $result->pagination->next_url;
    }
}
return $results;
}

这将拉取、解析,然后在浏览器中显示图像

  $all_url = 'https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}';
  $media = loopPages($all_url);
  foreach ($media->data as $post): ?>
    <!-- Renders images. @Options (thumbnail, low_resoulution, standard_resolution) -->
    <a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>"><img src="<?= $post->images->thumbnail->url ?>"></a>
<?php endforeach ?>

在PHP和许多面向对象的语言中$this是对当前对象(或调用对象)的引用。因为你的代码似乎不在任何类中$this不存在。查看此链接以获取 PHP 类和对象。

由于您刚刚在文件中定义了函数,因此您可以尝试使用 $result = fetchInstagramAPI($url); 调用函数(不带 $this )。

编辑

对于foreach,请检查$media->data是否实际上是一个数组,并尝试另一种我认为更容易阅读的语法。

编辑2

由于您现在知道$media的外观,因此您可以环绕另一个将遍历页面的 foreach 循环:

foreach ($media as $page){
  foreach ($page->data as $post) {
    echo '<!-- Renders images. @Options (thumbnail, low_resoulution, standard_resolution) -->';
    echo '<a class="group" rel="group1" href="' . $post->images->standard_resolution->url . '"><img src="' . $post->images->thumbnail->url . '"></a>';
  }
}