PDO - FETCH_CLASS - 将结果作为参数传递给构造函数

PDO - FETCH_CLASS - pass results to constructor as parameters(PDO - FETCH_CLASS - 将结果作为参数传递给构造函数)
本文介绍了PDO - FETCH_CLASS - 将结果作为参数传递给构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有什么办法可以将 PDO 的结果作为构造函数的参数传递?假设我有以下课程:

Is there any way, to pass results of PDO as parameters of the constructor? Let's say, I have the following class:

class Test
{
    private $value1;
    private $value2;
    function __construct($val1, $val2)
    {
        $this->value1 = $val1; $this->value2 = $val2;
    }
}

然后,通过 PDO 驱动程序,我从数据库中选择一些数据,让我们说:

Then, via PDO driver I select some data from DB, let's say:

SELECT price, quantity FROM stock

$results = $query->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "Test");

现在,PDO 将这些值直接传递给类字段,并绕过构造函数.

Right now, PDO passess these values directly to the class fields, and bypassing the constructor.

也许我遗漏了一些东西,但我想将查询的结果传递给构造函数.构造函数不能依赖于查询,我希望即使不使用 PDO 也能实例化这个类.

Maybe I am missing something, but I want to pass results from the query to the constructor. Constructor cannot be query-dependent, I want to be able to instantiate this class even without using PDO.

推荐答案

[我编辑了这个答案,因为我之前的答案不再准确.]

[I edited this answer as my previous answer is not accurate anymore.]

FETCH_CLASS 确实会获取私有属性.请参考这个答案.

FETCH_CLASS does fetch into private properties. Please refer to this answer.

这篇关于PDO - FETCH_CLASS - 将结果作为参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)