0

我正在尝试创建一个使用 cURL 向 Twitter API 发出请求的类。我已经对 PHP 中的面向对象编程进行了一些研究,但我不太清楚这应该如何工作。以下代码返回 NULL:

 <?php

    class twitter {

      public function curlQuery($url) {
      $ch = curl_init();

      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

      $json = curl_exec($ch);

      curl_close($ch);

      $array = json_decode($json);
      return var_dump($array);
      }
}

$object1 = new twitter;
$object1->url = "http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2";
$object1->curlQuery($object1->url);

 ?>

另外,我有点不确定何时在 PHP 类中使用$this->variablevs。$variable一个类中提到的所有变量不应该被引用为$this->variable?为什么你不想引用当前对象的变量?

4

2 回答 2

5

那么,为什么要将 url 存储在对象中,然后将该变量作为参数传递给同一对象的方法?似乎毫无意义,因为那时你可以做一些事情,比如:

$object1->url = 'blahblahblah';
$object1->curlQuery(); // <---note, no parameter

然后在 curlQuery 方法中:

curl_setopt($ch, CURLOPT_URL, $this->url);

至于PHP 中的$this->variablevs $variable$this->variable使该变量成为对象的成员。它将可用于对象中的所有方法。$variable其本身将只是单个方法中的局部变量。当该方法返回时,局部变量被销毁并且不再可用于其他方法。

简而言之,$this->variable用于您需要在对象内和多个方法调用中持久化的东西。用于$variable单一方法中的临时存储。

于 2012-06-09T05:30:17.897 回答
2

当变量被定义为类的属性时,在成员函数中使用它们时,您应该使用 $this->variablename。但这并不意味着类中提到的所有变量都被引用为 $this->variable

您可以通过其他方式在成员函数中使用局部变量。这将在定义的特定功能内具有范围。

喜欢

class twitter 
{
   var $apikey;

   function displayKey()
   {
     $k = 1;
     $this->apikey += $k;
     echo $this->apikey;
   }

 }

对于引用 apikey,我们使用 $this->apikey,对于函数内部的本地变量,我们使用相反的方式。

于 2012-06-09T05:29:24.660 回答