Page 1 of 1

OOP Vars Question

Posted: Sun Jan 04, 2004 3:15 pm
by DuFF
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?

Heres an example of what I'm asking:

Code: Select 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
        }
}
?>

Posted: Sun Jan 04, 2004 4:40 pm
by Sevengraff
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.

Posted: Sun Jan 04, 2004 4:59 pm
by DuFF
Ok, thanks for clearing that up. 8)

Re: OOP Vars Question

Posted: Sun Jan 04, 2004 10:48 pm
by infolock
DuFF wrote:

Code: Select 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
        }
}
?>

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...

ie :

Code: Select all

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());
   }
}