为了补充@Tadeck的答案,特别是关于如何实现可遍历对象的评论部分。我之所以提到stdClass
具体是因为PDOStatement实现了Traversable接口的PDO能力。这意味着实例(由PDO::query()和PDO::prepare()返回)可以用于数组特征函数,如(从 PHP 5.1 开始)。PDOStatement
foreach
因此,该方法getAllYears
不应由任何人实施stdClass
。唯一getAllYears
应该具有的功能是准备并返回一个实例,该PDOStatement
实例启动以将每一行结果作为对象返回(因此使用 stdClass 作为匿名对象),以便在 foreach 示例中使用(使用object operator
as in $year->yearID
)。
OPYears
类将有一个称为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;
}