pass constructor arguments using PDO::FETCH_CLASSTYPE

前端 未结 3 994
梦如初夏
梦如初夏 2021-01-16 16:05

I am replacing my old database layer by a new PDO based version.

However i have run into a problem:

When fetching objects using fetchObject i ca

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 16:28

    There doesn't seem to be a built-in solution. That part of the API doesn't look that good anyway. You could use a workaround:

    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    
    while ($row = $stmt->fetch()) {
        /* "Factory" */
        $obj = new $row['class_name_column']('constructor', 'args');
        unset($row['class_name_column']);
        foreach ($row as $key => $value) {
            $obj->$key = $value;
        }
        var_dump($obj);
    }
    

提交回复
热议问题