5

I am trying to learn PHP classes so I can begin coding more OOP projects. To help me learn I am building a class that uses the Rapidshare API. Here's my class:

<?php

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

    function apiCall($params)
    {
        echo $baseUrl;
    }
}

?>

$params will contain a set of key pair values, like this:

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

Which will later be appended to $baseUrl to make the final request URL, but I can't get $baseUrl to appear in my apiCall() method. I have tried the following:

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

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

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

And even tried $this->baseUrl = $baseUrl; in my apiCall() methid, I don't know what the hell I was thinking there though lol.

Any help is appreciated thanks :)

Josh
  • 277
  • 2
  • 4
  • 7

3 Answers3

14

Try

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

  function apiCall($params) {
    echo $this->baseUrl;
  }
}

I trust you are calling this code like so?

$rs = new RS;
$rs->apiCall($params);

Class attributes need to be prefixed with $this in PHP. The only exceptions are static methods and class constants when you use self.

Greg K
  • 10,770
  • 10
  • 45
  • 62
  • Hi, when I do that I get this error: `Fatal error: Cannot access empty property in C:\xampp\htdocs\RS_class\rs.class.php on line 9` – Josh Mar 25 '10 at 16:23
  • when i use `$this` within a function, i get this error : `Using $this when not in object context` – mrid Jan 11 '17 at 19:34
  • There is no instance (`$this`) within a function, as the error states, must be used in object context (within classes). – Greg K Nov 19 '18 at 10:44
3

Try this:

class C
{
    public $v = 'Hello, world!';

    function printHello()
    {
        echo $this->v;   // "Hello, world!"
    }
}

$obj = new C();
$obj->printHello();
John Feminella
  • 303,634
  • 46
  • 339
  • 357
0
function apiCall($params)
{
    echo $this->baseUrl;
}

You can access class variables int methods like this. When you use $this->baseUrl = $baseUrl; You change the value of class var $baseUrl with a local var $baseUrl which is probably NULL That why you are not getting any value back

Sinan
  • 5,819
  • 11
  • 39
  • 66