开发者

pass constructor arguments using PDO::FETCH_CLASSTYPE

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 can pass arguments for the object constructor.

However i am now porting over 开发者_JS百科a class which has several subclasses, all stored in the same table, and i want to use FETCH_CLASSTYPE. This means that i have to use the regular fetch() method to which i cant pass constructor arguments.

Is there another way to do this?

I could rename the constructor to something else and call it manually but i would like a clean solution.


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);
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜