tags:

views:

34

answers:

2

here is my code....

class line{
    function db($host, $user, $pass, $db){
        mysql_connect($host, $user, $pass) or die("Could Not Connect to Database or Database Does not Exists....");
        mysql_select_db($db) or die("Database Does not Exists....");
    }

    $idletime = 300;
    $deltime = 600;

     function test(){
    echo $idletime;
    echo idletime;
}

}

and calling this class as

$w = new line();
$w->test();

but it says

Undefined variable: idletime in *

please let me know what acutally the problem is...

+4  A: 

Your variable is a class property -- or, at least, I'm guessing that's what you want it to be...


This line inside your test method :

echo $idletime;

Is trying to access a variable defined inside that method -- not a class property.

And there is no such local variable -- hence the notice.


To access a class property, you need to use $this, this way :

echo $this->idletime;


Also, your code is not valid : you have to declare that your "variables" are indeed class properties -- i.e., you need to use some of the visibility keywords in front of them.

Here's you class, once re-written :

class line {
    function db($host, $user, $pass, $db) {
        mysql_connect($host, $user, $pass) or die("Could Not Connect to Database or Database Does not Exists....");
        mysql_select_db($db) or die("Database Does not Exists....");
    }

    protected $idletime = 300;
    protected $deltime = 600;

    public function test(){
        echo $this->idletime;
    }
}

I have :

  • Set your properties as protected
  • And I'm using $this to access them from inside the test method
  • I have also indicated the test method is public -- it's the default, but I like being explicit about it.


Don't hesitate to spend some time reading the Classes and Objects section of the manual : you'll learn lots of useful stuff ;-)

Pascal MARTIN
+1 I overlooked that $idletime is within the class. Deleted my answer.
Pekka
A: 

You need to pass the variables into your function call,

function test($idletime){
    echo $idletime;
    echo idletime;
}

Or it could be that the variable is out scope define them as global first

sico87
What about that line that says: echo idletime?
Vincent Ramdhanie