Robię sobie klasę kolekcji z książki PHP5 ZP.
Wszystko prawie działa, ale wyskakuje błąd o nadpisaniu klucza.
Kod wygląda tak:
StudentFaktory
public static function getStudent
($id){ $sql = "SELECT * FROM student WHERE student_id= '$id'";
return new Student($data['student_id'], $data['nazwa']);
}else{
throw new Exception("Student $id nie istnieje");
}
}
public static function getCoursesForStudent
($id, $col){ $sql = "SELECT kurs.kurs_id, kurs.kurs_kod, kurs.nazwa FROM kurs, student_kurs WHERE kurs.kurs_id = student_kurs.kurs_id AND student_kurs.student_id = '$id'";
echo '<pre>';print_r
($data);echo
'</pre>';
foreach ($data as $key => $datum){
$objCourse = new Course($datum['kurs_id'], $datum['kurs_kod'], $datum['nazwa']);
$col->addItem($objCourse, $objCourse->getCourseCode());
//echo '<pre>';print_r($col);echo '</pre>';
}
}
}
CourseClass
class Course {
private $_id;
private $_courseCode;
private $_name;
public $students;
function __construct($id, $courseCode, $name) {
$this->_id = $id;
$this->_courseCode = $courseCode;
$this->_name = $name;
//$this->students = new Collection();
//$this->students->setLoadCallback('_loadStudents', $this);
}
public function getName(){
return $this->_name;
}
public function getID(){
return $this->_id;
}
public function getCourseCode(){
return $this->_courseCode;
}
public function __toString() {
return $this->_name;
}
}
CollectionClass
class Collection implements IteratorAggregate{
private $_members = array(); private $_onload;
private $_isLoaded = false;
public function addItem($obj, $key = null){
$this->_checkCallback();
if($key){
if(isset($this->_members
[$key])){ throw new Exception("Klucz $key jest już zajęty");
}else{
$this->_members[$key] = $obj;
echo '<pre>';print_r
($this->_members
);echo
'</pre>'; }
}else{
$this->_members[] = $obj;
}
}
Test
$studentID = 1;
try{
$objStudent = StudentFactory::getStudent($studentID);
}catch (Exception $e){
//print_r($e);
die("Student #$studentID nie istnieje w bazie danych"); }
print $objStudent.' '. ($objStudent->courses->exist('INF101') ?
' jest ' : 'nie jest'). ' zapisany na kurs ';
Gdzie może być problem?