I´m trying to get all records from the database and then instantiate a new object with the data from each one:
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results){
for ($i=0; $i<count($results); ++$i){
$strValues = '';
$values = array_values($results[$i]);
for ($j=0; $j<count($values); ++$j){//Extract the values to pass them as arguments to the constructor below
if ($j == 0) $strValues .= $values[$j];
else{
$strValues .= ',';
$strValues .= '"'.$values[$j].'"';
}
}
eval('$result['.$i.'] = new '.get_class($this->instance).'('.$strValues.');');
}
}
The problem is that the object type can vary depending on if I'm querying the users or labels databases, so the call to constructor may be new User(user_id, username, name, surname) or new Label(label_id, name, description, color). The code above runs on the ObjectMapper class, which on creation gets assigned an object type and stores an instance of it in the private instance variable. This way I can get the name of the required constructor with get_class($this->instance).
I finally managed to make it work using an eval as shown, but I've read that this is not a good practice and I would like to know of better and cleaner ways to do it.