views:

56

answers:

1

I am building a class to send API calls to Rapidshare and return the results of said call. Here's how I want the call to be done:

$rs = new rs();

$params = array(
    'sub'   =>  'listfiles_v1',
    'type'  =>  'prem',
    'login' =>  '10347455',
    'password'  =>  'not_real_pass',
    'realfolder'    => '0',
    'fields'    => 'filename,downloads,size',
    );

print_r($rs->apiCall($params));

And here's the class so far:

class RS
{
    var $baseUrl = 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=';

    function apiCall($params)
    {
        $newUrl = $baseUrl;
        $keys = array_keys($params);
        $count = count($params);
        for($i = 0; $i < $count; $i++)
        {
            $newUrl .= $keys[$i];
            $newUrl .= '&';
            $newUrl .= $params[$keys[$i]];
        }
        return $newUrl;
    }
}

Obviously i'm returning $newUrl and using print_r() to test the query string, and this is what it comes out as with the code shown above:

sub&listfiles_v1type&premlogin&10347455password&_not_real_passrealfolder&0fields&filename,downloads,size

When it should be:

http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=listfiles_v1&amp;type=prem&amp;login=10347455&amp;password=not_real_pass&amp;realfolder=0&amp;fields=filename,downloads,size

Hopefully you can see what I'm trying to do here :P It's probably a silly mistake that I'm failing to find or a logical error.

Thanks in advance.

+1  A: 

You should have:

$newUrl = $this->baseUrl;

You need to use $this to refer to members of that class from within that class. Also don't use var to declare members. It's PHP4 and (afaik) deprecated. Instead use private (etc.

Lastly, your loop to create the parameters can be greatly simplified and the logic isn't correct for what you want to achieve. Try:

class RS {
  private $baseUrl = 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?';

  function apiCall($params) {
    $newUrl = $this->baseUrl;
    foreach ($params as $k => $v) {
      $newUrl .= urlencode($k) . '=' . urlencode($v) . '&';
    }
    return $newUrl;
  }
}

Or, even better, use http_build_query():

class RS {
  private $baseUrl = 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?';

  function apiCall($params) {
    return $this->baseUrl . http_build_query($params);
  }
}
cletus