pass constructor arguments using PDO::FETCH_CLASSTYPE

前端 未结 3 993
梦如初夏
梦如初夏 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);
    }
    
    0 讨论(0)
  • 2021-01-16 16:35

    I think it's perfectly clean to call an initializing-method on the returned instance right after the fetch.

    0 讨论(0)
  • 2021-01-16 16:40

    It's a PHP bug reported as #62567

    You may work around it by passing as a second argument any classname with a constructor

    0 讨论(0)
提交回复
热议问题