doukan5332 2011-07-13 22:08
浏览 27

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

  • 写回答

3条回答 默认 最新

  • duai4379 2011-07-14 10:20
    关注

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

报告相同问题?

悬赏问题

  • ¥20 simulink单相桥式整流电路
  • ¥35 问问51单片机流水灯的代码该怎么写
  • ¥15 关于#百度#的问题:感觉已经将字体段落、字体、页边距、纸张大小、文档网络调成与论文模板一致,为什么黄色部分字体左右的间距还是不一样啊,求私信发文件接收看一下
  • ¥15 stata webuse报错
  • ¥15 TypeError: Cannot read properties of undefined (reading 'status')
  • ¥15 如何利用AI去除图片中的竹架子
  • ¥15 python 写个基金爬取的代码,自动卖出功能
  • ¥15 Linux系统启动不起来
  • ¥15 为什么运行仿真数码管不亮(语言-c语言)
  • ¥15 陈仁良《直升机飞行动力学》小扰动线化方程如何推导