I am trying to use a structure class so I can use with various classes with same layout. The idea is to access different tables on database with their columns. It works fine but when trying to use multiple variables it overrides previous variables. I want to define new object only once and load data into different variables.
Structure.Class:
class Structure
{
private $tbl;
private $info = Array();
public function __construct($tbl)
{
global $db;
$cols = $db->query("SHOW COLUMNS FROM " . $tbl)->fetchAll();
foreach ($cols as $col):
$this->info[$col['Field']] = null;
endforeach;
$this->tbl = $tbl;
}
public function load($id)
{
global $db;
$select = $db->query("SELECT * FROM ".$this->tbl." WHERE id = ?", $id);
$helper = Array();
if ($select->numRows() > 0)
{
$results = $select->fetchArray();
foreach ($results as $key => $r):
$this->info[$key] = $r;
endforeach;
return $this;
}
return false;
}
public function __get($name)
{
return $this->info[$name] ?? false;
}
}
User.Class:
class User extends Structure
{
private static $table = "users";
public function __construct()
{
parent::__construct(self::$table);
}
}
Usage:
$c['User'] = new User();
$u1 = $c['User']->load(1);
echo $u1->__get('id') . "<hr>";
$u2 = $c['User']->load(2);
echo $u2->__get('id') . "<hr>";
echo $u1->__get('id') . "<hr>";
Why does the last load overrides the first one? And how can I fix it? Thanks!