1--TEST-- 2PDO Common: PDOStatement SPL iterator 3--SKIPIF-- 4<?php # vim:ft=php 5if (!extension_loaded('pdo')) die('skip'); 6if (!extension_loaded('SPL')) die('skip SPL not available'); 7if (!class_exists('IteratorIterator', false)) die('skip IteratorIterator class not present'); 8$dir = getenv('REDIR_TEST_DIR'); 9if (false == $dir) die('skip no driver'); 10require_once $dir . 'pdo_test.inc'; 11PDOTest::skip(); 12?> 13--FILE-- 14<?php 15if (getenv('REDIR_TEST_DIR') === false) putenv('REDIR_TEST_DIR='.dirname(__FILE__) . '/../../pdo/tests/'); 16require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc'; 17$db = PDOTest::factory(); 18 19$db->exec('CREATE TABLE test(id int NOT NULL PRIMARY KEY, val VARCHAR(10), grp VARCHAR(10))'); 20$db->exec('INSERT INTO test VALUES(1, \'A\', \'Group1\')'); 21$db->exec('INSERT INTO test VALUES(2, \'B\', \'Group2\')'); 22$SELECT = 'SELECT val, grp FROM test'; 23 24class Test 25{ 26 function __construct($name = 'N/A') 27 { 28 echo __METHOD__ . "($name)\n"; 29 } 30} 31 32$stmt = $db->query($SELECT, PDO::FETCH_CLASS, 'Test', array('WOW')); 33 34$it = new IteratorIterator($stmt); /* check if we can convert that thing */ 35 36/*** HINT: If YOU plan to do so remember not to call rewind() -> see below ***/ 37 38foreach($it as $data) 39{ 40 var_dump($data); 41} 42 43$it->next(); /* must be allowed */ 44var_dump($it->current()); /* must return NULL */ 45var_dump($it->valid()); /* must return false */ 46 47class PDOStatementAggregate extends PDOStatement implements IteratorAggregate 48{ 49 private function __construct() 50 { 51 echo __METHOD__ . "\n"; 52 $this->setFetchMode(PDO::FETCH_NUM); 53 /* default fetch mode is BOTH, so we see if the ctor can overwrite that */ 54 } 55 56 function getIterator() 57 { 58 echo __METHOD__ . "\n"; 59 $this->execute(); 60 return new IteratorIterator($this, 'PDOStatement'); 61 } 62} 63 64$stmt = $db->prepare($SELECT, array(PDO::ATTR_STATEMENT_CLASS=>array('PDOStatementAggregate'))); 65 66foreach($stmt as $data) 67{ 68 var_dump($data); 69} 70 71?> 72--EXPECTF-- 73Test::__construct(WOW) 74object(Test)#4 (2) { 75 ["val"]=> 76 string(1) "A" 77 ["grp"]=> 78 string(6) "Group1" 79} 80Test::__construct(WOW) 81object(Test)#6 (2) { 82 ["val"]=> 83 string(1) "B" 84 ["grp"]=> 85 string(6) "Group2" 86} 87NULL 88bool(false) 89PDOStatementAggregate::__construct 90PDOStatementAggregate::getIterator 91array(2) { 92 [0]=> 93 string(1) "A" 94 [1]=> 95 string(6) "Group1" 96} 97array(2) { 98 [0]=> 99 string(1) "B" 100 [1]=> 101 string(6) "Group2" 102} 103