To supplement on @Tadeck answer, specifically the comment section on how to implement a traversable object. The reason why I mentioned stdClass was specifically due to PDOs ability that PDOStatement implements the Traversable interface. This means that the PDOStatement instance (returned by PDO::query() and PDO::prepare()) can be used in array featured functions like foreach (as of PHP 5.1).
The method getAllYears should therefor not be implemented by any stdClass. The only function getAllYears should have is prepare and return a PDOStatement instance initiated to return each row result as an object (therefor the use of stdClass as an anonymous object) in order to be used in the foreach example (using the object operator as in $year->yearID).
The OP Years class would have a method called getAllYears() which queries the results.
Implementation example:
// 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;
}
}
Demo:
$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;
}