Defining a variable in a class and using it in functions
15,714
Solution 1
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
.
Solution 2
Try this:
class C
{
public $v = 'Hello, world!';
function printHello()
{
echo $this->v; // "Hello, world!"
}
}
$obj = new C();
$obj->printHello();
Author by
Josh
Updated on July 06, 2022Comments
-
Josh almost 2 years
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 myapiCall()
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 myapiCall()
methid, I don't know what the hell I was thinking there though lol.Any help is appreciated thanks :)