php - Overriding fetch() for PDO when fetching using foreach -
i have extended pdostatement
, modified fetch()
method typecast values of types timestamp , arrays, in postgresql, datetime , native array. works intended can't override behaviour when using statement in foreach.
i have solved returning rows object implementing arrayaccess, iteratoraggregate , countable. i'm not satisfied solution , want pure array back.
example:
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 example(name) values('test')"); // $s = $db->prepare("select * example"); $s->execute(); foreach ($s $r) { var_dump($r); } $s->closecursor(); // how want $s = $db->prepare("select * example"); $s->execute(); while ($r = $s->fetch()) { var_dump($r); } $s->closecursor(); // how want $s = $db->prepare("select * example"); $s->execute(); var_dump($s->fetch()); $s->closecursor();
output:
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) }
the pdostatement
class implements built-in internals-only traversable
interface. iterator implements bypasses public pdostatement::fetch()
method.
Comments
Post a Comment