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:
- 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.
- 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.
- 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.
精彩评论