php Collection类的设计
用。net开发已经很多年了,最近接触到php,发现php也没好玩。不过发现它里面没有集合类,只有数组,并且数组很强。这里我用数组来包装成一个集合Collection,代码如下:
class CourseCollection extends Collection { public function addItem(Course $obj,$key=null) {parent::addItem($obj,$key);}}class Student{private $_id;private $_name;public $course;publicfunction __construct($id,$name){$this->_id=$id;$this->_name=$name;$this->course=new CourseCollection();$this->course->setLoadCallback('loadCourses',$this);}public function getName(){return $this->_name;}public function getID(){return $this->_id;}public function __toString(){return $this->_name;}public function loadCourses(Collection $col){$col->addItem(new Course(1, "001", "语文"),1);$col->addItem(new Course(2, "002", "数学"),2);}}调用代码如下:
$student=new Student(1, "majiang");
print $student->getName();
print $student->course->getItem(1);