@Tadeckの回答、特にトラバース可能なオブジェクトの実装方法に関するコメントセクションを補足します。私が言及した理由は、stdClass
特にPDOStatementがTraversableインターフェースを実装するというPDOの機能によるものです。これは、インスタンス ( PDO::query()およびPDO::prepare()によって返される) を(PHP 5.1 以降) のような配列フィーチャー関数で使用できることを意味します。PDOStatement
foreach
したがって、このメソッドgetAllYears
は、どの .xml ファイルでも実装しないでstdClass
ください。foreach の例で ( as のas を使用して) 使用するために必要な唯一の関数は、各行の結果をオブジェクトとして返すように開始されgetAllYears
たインスタンスを準備して返すことです (したがって、匿名オブジェクトとして stdClass を使用します)。PDOStatement
object operator
$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;
}