補充@Tadeck答案,特別是關於如何實現可遍歷對象的comment部分。我之所以提到stdClass
是因爲PDOs的能力,PDOStatement實現了Traversable接口。這意味着PDOStatement
實例(由PDO::query()和PDO::prepare()返回)可用於數組特色功能,如foreach
(自PHP 5.1起)。
該方法getAllYears
不應該由任何stdClass
執行。唯一的函數getAllYears
應該準備並返回一個PDOStatement
實例,以便將每個行結果作爲對象返回(爲此,將stdClass用作匿名對象),以便在以前的示例中使用(使用object operator
,如$year->yearID
) 。
該OP Years
類將有一個方法稱爲getAllYears()
查詢結果。 實現示例:
// an example of the Years class implementing getAllYears
class Years {
public function getAllYears() {
// pseudo variable representing your original PDO object
// being used somehow.
$conn = new PDO();
// prepare a statement selecting all years
$stmt = $conn->prepare(" select all years ");
// set the fetch mode to return an anonymous object,
// mapping column names to properties, on each iteration
$stmt->setFetchMode(PDO::FETCH_OBJ);
// return the statement if no SQL errors occurred
// implement the way you would handle any SQL errors
if(!$stmt->execute())
throw new Exception('exception thrown: SQL error');
return $stmt;
}
}
演示:
$Years = new Years;
// the PDOStatement returned can be immediately used for iteration
foreach($Years->getAllYears() as $year) {
// $year represents an anonymous object, each column is a property
// of this object
$year->yearID;
$year->yearName;
}
來源
2013-08-04 12:56:48
dbf
將是很好的闡述OP如何能夠返回一個迭代(stdClass的)從SQL操作返回。 – dbf
@dbf:我認爲問題只是迭代。不過,會在答案中增加更多信息。 – Tadeck
非常感謝您的回答。我希望闡述能夠在將來幫助某人。 – etoipi