dongrang9300 2013-03-21 09:48
浏览 95
已采纳

如何使用PDO的FETCH_CLASS分配构造函数参数?

I want to create instances of objects using PDO. I know that there's plently of questions already but I have only found that it is possible to send an array of paramters to a constructor. To me it seems that the constructor can only accept an array as argument. However this would make the constructor less meaningful.

I want to create a class with my own getters and setters like this:

class MyClass {
    private propertyA
    private propertyB

    public __constructor($argA, $argB) {
        $this->setPropertyA($argA);
        $this->setPropertyB($argB);
    }

    public setPropertyA($arg) {
        $this->proprtyA = $arg;
    }
}

Is there an elgant way to create an instance of such a class using data from a database, preferably using PDO.

  • 写回答

1条回答 默认 最新

  • dsyo9700 2013-03-22 16:08
    关注

    Freeballin' here:

    $handle = new PDO("blahblahblah");
    $statement = $handle->prepare("SELECT blahblah");
    $statement->execute();
    $object_params = $statement->fetch(PDO::FETCH_ASSOC);
    
    $object = new Object($object_params);
    // OR...
    $object = new Object($object_params["col_1"], $object_params["col_2"], "etc.");
    

    Alternatively:

    class MyClass {
        private propertyA
        private propertyB
    
        public __constructor() {
            $handle = new PDO("blahblahblah");
            $statement = $handle->prepare("SELECT blahblah");
            $statement->execute();
            $object_params = $statement->fetch(PDO::FETCH_ASSOC);
    
            $this->setPropertyA($object_params[$argA_key]);
            $this->setPropertyB($object_params[$argB_key]);
        }
    
        public setPropertyA($arg) {
            $this->proprtyA = $arg;
        }
    }
    

    I don't know what you're looking for exactly. Could you comment?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改