Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP动态获取类构造函数并调用它来创建新实例_Php_Mysql_Oop_Pdo - Fatal编程技术网

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

PHP动态获取类构造函数并调用它来创建新实例,php,mysql,oop,pdo,Php,Mysql,Oop,Pdo,我试图从数据库中获取所有记录,然后用每个记录中的数据实例化一个新对象: $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

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

$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.');');              
        }
    }
$stmt=$this->pdo->prepare('SELECT*FROM'.$this->table.'ORDER BY'.$ORDER.ASC');
$stmt->execute();
$results=$stmt->fetchAll(PDO::FETCH_ASSOC);
如果(结果){

对于($i=0;$i这应该可以实现您想要实现的目标。不要使用
eval

PDO有很多有用的获取模式,下面对它们进行了描述


另外,请记住正确地将表名和
$order
变量列为白名单。

为了便于将来参考,当您不打算在同一“层”中迭代结果时,最好使用
fetchAll()
。如果您打算立即对结果集执行迭代过程,则应使用循环
fetch()
呼叫。非常感谢您的帮助!我使用fetch\u all()因为这是为视图准备$result数组以便在以后的步骤中显示的控制器。但是这仍处于早期开发阶段,我的想法是限制查询中的结果不会有太多的负载。再次感谢您的回答,我一直走错了方向。
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_CLASS, get_class($this->instance));