If this works..
$stmt = DB::$db->query('SELECT * FROM users');
while ($r = $stmt->fetch()) { print_r($r); }
Is there any way possible to get something like this to work?
function fetch() {
$stmt = DB::$db->query('SELECT * FROM users');
return $stmt->fetch();
}
while ($r = fetch()) { print_r($r); }
UPDATE
Or maybe if it's in a class it can work by using some sort of class iterator extension/implementation?
class User {
public static function fetch() {
$stmt = DB::$db->query('SELECT * FROM users');
return $stmt->fetch();
}
}
while ($r = User::fetch()) { print_r($r); }
SOLUTION
Well I did end up finding a working solution, but the accepted answer which uses a generator is probably the better way to go.
class User {
private static $stmt;
public static function fetch() {
if (static::$stmt === null) {
static::$stmt = DB::$db->query('SELECT * FROM users');
}
return static::$stmt->fetch();
}
}
while ($r = User::fetch()) { print_r($r); }