duanpu8830 2012-06-09 05:22
浏览 40
已采纳

在PHP类中创建cURL方法

I'm trying to create a class that uses cURL to make requests to the Twitter API. I've done some research on object oriented programming in PHP, and I can't quite figure out how this should work. The following code returns 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);

 ?>

Also, I'm a little unsure when to use $this->variable vs $variable in a PHP class. Shouldn't all variables mentioned in an class be referenced as $this->variable? Why would you ever not want to reference the variable of the current object?

  • 写回答

2条回答 默认 最新

  • douren0558 2012-06-09 05:30
    关注

    Well, why are you storing the url in the object, then passing that variable as a parameter to a method of that same object? Seems pointless, because then you could do somethign like:

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

    and then in the curlQuery method:

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

    As for $this->variable v.s. $variable in PHP, $this->variable makes that variable a member of the object. It'll be available to all the methods in the object. $variable by itself will simply be a local variable within a single method. When that method returns, the local variable is destroyed and is no longer available to other methods.

    In short, use $this->variable for things you need persisted within the object and across multiple method calls. Use $variable for temporary storage within a single method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?