Page 1 of 1
Quick class question
Posted: Thu Mar 15, 2007 10:24 am
by aspekt9
Alright, I put all my news functions into a class and I just have a quick question. would I declare the variables I want to use in every function like this?:
Code: Select all
var $monthp = $_POST['theMonth'];
var $day = $_POST['theDay'];
var $year = $_POST['theYear'];
var $hours = $_POST['theHour'];
Then reference them as $this->day, $this->year etc?
Because it returns an error:
Parse error: parse error, unexpected T_VARIABLE on each of those lines.
Posted: Thu Mar 15, 2007 10:47 am
by mentor
you can't do like this. Try something like
Code: Select all
class test
{
var $monthp = null;
var $day = null;
var $year = null;
var $hours = null;
function test()
{
$this->monthp = $_POST['theMonth'];
$this->day = $_POST['theDay'];
$this->year = $_POST['theYear'];
$this->hours = $_POST['theHour'];
}
}
$obj = new test();
echo $obj->monthp;
Posted: Thu Mar 15, 2007 10:50 am
by aspekt9
The only problem is that I want to use all those values in more than one function so I don't want to declare them each time I want to call a function. I want them to be kind of like global variables throughout each function.
Posted: Thu Mar 15, 2007 10:59 am
by mentor
Posted: Thu Mar 15, 2007 11:01 am
by Kieran Huggins
if you declare a local variable inside a method they're local only. To share them with the object (and other members) you have to use the $this->var syntax, and you should declare them at the beginning as mentor suggested.
It's ok to mix them:
Code: Select all
class test
{
var $objectVar = null;
function test()
{
$localVar = 'bob'; // isolated local variable
$this->objectVar = 'frank'; // available to all methods as well as externally
echo $localVar.' spanks '.$this->objectVar;
}
}
$t = new test;
$t->test(); // prints 'bob spanks frank'
echo $t->objectVar; // prints 'frank'
Posted: Thu Mar 15, 2007 11:11 am
by mentor
Kieran, thank you for explaining

Posted: Thu Mar 15, 2007 2:50 pm
by aspekt9
I've been doing that. I set all var = null; then give values to them in a function as $this->year = $_POST['year']; but when I go to use $this->year in another function it doesn't return anything.
Posted: Thu Mar 15, 2007 2:54 pm
by Luke
post your code
Posted: Thu Mar 15, 2007 3:07 pm
by aspekt9
Actually I figured it out, the function name that stores the constructs had to be the same name as the class

thanks for all the help guys.