Dynamic variable scope in extended classes
Posted: Wed Aug 21, 2013 7:39 am
Hello, I have a base class where I have my set and get functions, as such:
Then, that class is the base of all my other classes. The db class is mysqli_extends. My question is, when I extend the class, like this:
as Thing gets extended, new variables are added based on database field names, which in turn are used to title my microdata tags (The basis for these classes is to parallel what I'm seeing at schema.org). Is there a better way than to use global variables? Will this cause issues if I use extend my Thing class with, say Article. Then, on in my Page class, which also extends Thing, I use my Article class. Are the global variables going to get over written?
Code: Select all
class Utilities{
function __construct(){
global $db;
$this->db =& $db;
}
// GET function for all properties
function get($property){
global $$property;
return $this->$property;
}
// SET function for all properties
function set($property, $value){
global $$property;
if (is_object($$property)){
// incomplete
}else{
$this->$property = $value;
}
}
}
Code: Select all
class Thing extends Utilities{
// GET id in constuct and build thing
// (if this is a new object, be sure to pass 0 to $thingId)
public function __construct($thingId, $newArray = array()){
parent::__construct();
if($thingId > 0){
$this->set('thing', $thingId);
$query = "SELECT * FROM thing WHERE id = '".$thingId."'";
$dataArray = $db->query($query)->fetch_assoc();
// CREATE variables from data
foreach($dataArray as $k=>$v){
$this->set($k, $v);
}
return $thingId;
}else{
// we're going to make a new one.
// CREATE the data table
$this->db->insert('thing', $newArray);
foreach($newArray as $k=>$v){
//parent::set($k, $v);
$this->set($k, $v);
}
// RETURN the new id
$this->set('thing', $this->db->insert_id);
return $this->db->insert_id;
}
}
public function save(){
// SAVE all portions that are part of Thing
$dataArray = array('additionalType' => $this->get('additionalType'), 'description' => $this->get('description'), 'image' => $this->get('image'), 'name' => $this->get('name'));
$this->db->update('thing', $dataArray, 'id = "'.$this->get('thing').'"');
return $this->get('thing');
}
}