开发者

class variables - when to use them

开发者 https://www.devze.com 2023-04-11 05:23 出处:网络
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

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消