PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I can't really find a definitive answer anywhere online so I thought I'd ask you guys. When do I need to define a class var? I have seen some classes that use no class vars, and just create new ones as they go while other classes define every variable used. So I guess my question is, do I need to at all?
<?php
class foo
{
var $bar = 0;
// var $sentence; are these necessary?
// var $output; are these necessary?
function output($sentence)
{
echo $sentence; // Do I need to define the var $sentence?
}
function output2($sentence)
{
$output = trim($sentence); // Do I need to define the var $output?
echo $output;
}
function addten()
{
$this->bar = $this->bar + 10; // I'm pretty sure this needs to be defined
}
}
?>
The $sentance and $output don't need to be defined since they are local to the one method, but if you want to be able to access a var in the whole class, you should declare them up there with $bar.
Usually you should have all your var statements, then give them values in the constructor.
<?php
class foo
{
var $bar = 0;
// var $sentence; are these necessary?
// var $output; are these necessary?
function output($sentence)
{
echo $sentence; // Do I need to define the var $sentence?
}
function output2($sentence)
{
$output = trim($sentence); // Do I need to define the var $output?
echo $output;
}
function addten()
{
$this->bar = $this->bar + 10; // I'm pretty sure this needs to be defined
}
}
?>
Just adding to Sevengraff..
you dont' *have* to declare the variables before the functions just so ya know. You *should* if you plan on using that same var throughout the rest of your class ( as Sevengraff pointed out ).
I always define all my variables I want to use at the beginning, then, when I'm gonna add flags to the function tiself, I use temporary variables and then reassign those values to my global vars just incase i am wanting to predifine them...
class foo
{
var $bob = 'my_db';
function select_db($data)
{
$this->bob = $data; // if data has been set, reassign the value to $bob, otherwise, use default value
mysql_select_db($this->bob) or die(mysql_error());
}
}