pass constructor arguments using PDO::FETCH_CLASSTYPE

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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 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.

回答1:

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


回答2:

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



回答3:

It's a PHP bug reported as #62567

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!