从php中的类调用函数

时间:2011-11-11 02:27:05

标签: php function

我在这堂课的某些课程中有一堂课。所有函数都有变量。代码写在下面

<?php
class myclass{
    public function getresults{
        $url = 'http://www.slideshare.net/api/2/search_slideshows?q=google';
        echo $url;
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');
        $query = curl_exec($ch);
        $errorCode = curl_errno($ch); 
        curl_close($ch);
        $array = (array) simplexml_load_string($query);
        //echo '<pre>';
        //print_r($array);
        public $TotalResults;
        $TotalResults = $array['Meta']->TotalResults;
        echo "function is correct";
    }

}

当我称之为有趣

echo $obj1->TotalResults;

这给我带来了错误。请帮助我并修改我的代码。

2 个答案:

答案 0 :(得分:1)

您错误地使用了成员变量:

class myclass{
    public $TotalResults; // <-- added member variable
    public function getresults{
        $url = 'http://www.slideshare.net/api/2/search_slideshows?q=google';
        echo $url;
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');
        $query = curl_exec($ch);
        $errorCode = curl_errno($ch); 
        curl_close($ch);
        $array = (array) simplexml_load_string($query);
        //echo '<pre>';
        //print_r($array);
        $this->TotalResults = $array['Meta']->TotalResults; // <-- corrected
        echo "function is correct";
    }
}

并且在您执行$obj->getresults()之后(其中$obj必须由$obj = new myclass();实例化之前),$obj->TotalResults应该包含您想要的内容。

有帮助吗?

答案 1 :(得分:0)

这样的事情:

<?php
 class myclass {

  public function getresults()
  {
    $url = 'http://www.slideshare.net/api/2/search_slideshows?q=google';
    echo $url;
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');
    $query = curl_exec($ch);
    $errorCode = curl_errno($ch); 
    curl_close($ch);
    $array = (array) simplexml_load_string($query);
    //echo '<pre>';
    //print_r($array);
    public $TotalResults;
    $TotalResults = $array['Meta']->TotalResults;
    echo "function is correct";
  }
}

$obj = new myclass;
echo $obj1->getresults();