user656925
user656925

Reputation:

class variables - when to use them

How does one know when to put variables into the class rather than inside the class functions? For example - This database class is instantiated by its sub-class and it also instantiates its sub-class. It has no class variables.

class database extends one_db      
{
    function __construct()  
    {
        one_db::get();
    }

    public function pdo_query()
    {
    }

    public function query($query) 
    {
        return one_db::$db->query($query);
    }

    private function ref_arr(&$arr)  // pdo_query will need this later. 
    { 
        $refs = array(); 
        foreach($arr as $key => $value) 
        {  
            $refs[$key] = &$arr[$key];
        } 
        return $refs;
    }   
}

Howeve I could just as well pull out the $query variabe like this

class database extends one_db      
{
    protected $query;

    function __construct()  
    {
        one_db::get();
    }

    public function pdo_query()
    {
    }

    public function query($query) 
    {
        $this->query=$query
        return one_db::$db->query($this->query);
    }

    private function ref_arr(&$arr)  // pdo_query will need this later. 
    { 
        $refs = array(); 
        foreach($arr as $key => $value) 
        {  
            $refs[$key] = &$arr[$key];
        } 
        return $refs;
    }   
}

I would assume that this only needs to be done when the variable is shared between multiple class functions but I'm not too sure.

Upvotes: 1

Views: 113

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174957

There are 3 types on variables to be used in a class/object:

  1. An instance variable - to be used as an object-wide variable, which all methods should have access to. Saving a databse connection is a good idea for an instance variable.
  2. A static variable - to be used when there is no need for an object instance. A static counter of some some sort is usually a static variable.
  3. A method variable - which is only contained within its function. Internal methodical variables should go in this category.

Your choice depending on your needs.

Upvotes: 1

user229044
user229044

Reputation: 239311

Use instance variables for state you want to associate with the object. If you want the DB class to remember the last query, store it as part of the class. Otherwise, simply pass it along to the parent class.

Upvotes: 0

Related Questions