文章教程

PHP基于SPL实现的迭代器模式示例

5/9/2018 9:52:38 PM 人评论 次浏览

本文实例讲述了PHP基于SPL实现的迭代器模式。分享给大家供大家参考,具体如下:

现在有这么两个类,Department部门类、Employee员工类:

//部门类
class Department{
  private $_name;
  private $_employees;
  function __construct($name){
    $this->_name = $name;
    $this->employees = array();
  }
  function addEmployee(Employee $e){
    $this->_employees[] = $e;
    echo "员工{$e->getName()}被分配到{$this->_name}中去";
  }
}
//员工类
class Employee{
  private $_name;
  function __construct($name){
    $this->_name = $name;
  }
  function getName(){
    return $this->_name;
  }
}
//应用:
$lsgo = new Department('LSGO实验室');
$e1 = new Employee("小锦");
$e2 = new Employee("小猪");
$lsgo->addEmployee($e1);
$lsgo->addEmployee($e2);