提问者:小点点

PHP动态获取类构造函数并调用它来创建一个新实例[duplicate]


我试图从数据库中获取所有记录,然后用每个记录中的数据实例化一个新对象:

$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.');');              
        }
    }

问题是,对象类型可能因我查询的是用户还是标签数据库而异,因此对构造函数的调用可能是新用户(user_id,username,name,surname)或新标签(label_id,name,description,color)。 上面的代码运行在ObjectMapper类上,该类在创建时获得一个对象类型,并将其实例存储在私有实例变量中。 这样,我就可以用get_class($this->instance)获得所需构造函数的名称。

我最终设法使它工作使用一个评估如图,但我读到这不是一个好的实践,我想知道更好和更干净的方式来做它。


共1个答案

匿名用户

这应该能达到你想要达到的目的。 不要使用评估

PDO有很多有用的提取模式,这里介绍了https://phpdelusions.net/PDO/fetch_modes#fetch_class

$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_CLASS, get_class($this->instance));

附注。 记住要正确地将表名和$order变量列入白名单。