gpt4 book ai didi

php - 使用 foreach 获取时覆盖 PDO 的 fetch()

转载 作者:搜寻专家 更新时间:2023-10-31 20:55:18 25 4
gpt4 key购买 nike

我已经扩展了PDOStatement并修改了 fetch()将 PostgreSQL 中时间戳和数组类型的值强制转换为 DateTime 和 native 数组的方法。这按预期工作,但在 foreach 中使用该语句时我无法覆盖该行为。

我通过将行返回到实现 ArrayAccess、IteratorAggregate 和 Countable 的对象中解决了这个问题。但是我对该解决方案不满意,只想返回一个纯数组。

例子:

class ExtendedStatement extends PDOStatement {    protected function __construct() {        $this->setFetchMode(PDO::FETCH_ASSOC);    }    public function fetch(        $fetch_style = PDO::FETCH_ASSOC,        $cursor_orientation = PDO::FETCH_ORI_NEXT,        $cursor_offset = 0)    {        $r = parent::fetch($fetch_style, $cursor_orientation, $cursor_offset);        if (is_array($r)) {            $r["extradata"] = TRUE;        }        return $r;    }}$db = new PDO("sqlite::memory:");$db->setAttribute(    PDO::ATTR_STATEMENT_CLASS, array("ExtendedStatement", array($db)));$db->exec("CREATE TABLE example(id INTEGER PRIMARY KEY, name VARCHAR)");$db->exec("INSERT INTO example(name) VALUES('test')");// This is what is does$s = $db->prepare("SELECT * FROM example");$s->execute();foreach ($s as $r) {    var_dump($r);}$s->closeCursor();// This is how I want it to be$s = $db->prepare("SELECT * FROM example");$s->execute();while ($r = $s->fetch()) {    var_dump($r);}$s->closeCursor();// This is how I want it to be$s = $db->prepare("SELECT * FROM example");$s->execute();var_dump($s->fetch());$s->closeCursor();

输出:

array(2) {  ["id"]=>  string(1) "1"  ["name"]=>  string(4) "test"}array(3) {  ["id"]=>  string(1) "1"  ["name"]=>  string(4) "test"  ["extradata"]=>  bool(true)}array(3) {  ["id"]=>  string(1) "1"  ["name"]=>  string(4) "test"  ["extradata"]=>  bool(true)}

最佳答案

PDOStatement 类实现了内置的仅限内部的Traversable 接口(interface)。它实现的迭代器绕过公共(public) PDOStatement::fetch() 方法。

关于php - 使用 foreach 获取时覆盖 PDO 的 fetch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3333141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com