Bug #52444 [Opn]: Extending PDOStatement and replacing fetch() apply when using foreach
| From: | cmb@php.net | Date: | Thu, 02 Apr 2020 09:56:58 +0000 |
| Subject: | Bug #52444 [Opn]: Extending PDOStatement and replacing fetch() apply when using foreach | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-226407@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=52444&edit=1
ID: 52444
Updated by: cmb@php.net
Reported by: antennen at gmail dot com
Summary: Extending PDOStatement and replacing fetch() apply
when using foreach
Status: Open
Type: Bug
-Package: PDO SQLite
+Package: PDO Core
Operating System: All
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
> PDO should rather implement the Iterator interface so one can
> override "current"
ACK. And PHP 8 would likely be suitable for this change.
By the way, this is a general PDO issue, not only for PDO SQLite.
Previous Comments:
------------------------------------------------------------------------
[2010-11-26 13:31:18] johannes@php.net
PDO should rather implement the Iterator interface so one can override "current"
------------------------------------------------------------------------
[2010-07-26 12:57:39] antennen at gmail dot com
Description:
------------
Extending PDOStatement and replacing fetch() doesn't work when iterating using foreach. It
calls the built in fetch rather than my overridden one. This can be circumvented using while($r =
$s->fetch()) { .. } but I believe this behaviour is unexpected.
Test script:
---------------
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')");
$s = $db->prepare("SELECT * FROM example");
$s->execute();
foreach ($s as $r) {
var_dump($r);
}
Expected result:
----------------
array(3) {
["id"]=>
string(1) "1"
["name"]=>
string(4) "test"
["extradata"]=>
bool(true)
}
Actual result:
--------------
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(4) "test"
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=52444&edit=1