简体   繁体   English

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

[英]How do I use PDO's FETCH_CLASS to assign constructor arguments?

I want to create instances of objects using PDO. 我想使用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: 我想用我自己的getter和setter创建一个类,如下所示:

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. 有没有一种方法可以使用数据库中的数据创建这样一个类的实例,最好使用PDO。

Freeballin' here: Freeballin'在这里:

$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? 你能评论吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM