我们使用这种方式重构 Department 类:
classDepartmentimplementsIterator
{private$_name;
private$_employees;
private$_position;//标志当前数组指针位置function__construct($name)
{$this->_name = $name;
$this->employees = array();
$this->_position = 0;
}
functionaddEmployee(Employee $e)
{$this->_employees[] = $e;
echo"员工{$e->getName()}被分配到{$this->_name}中去";
}
//实现 Iterator 接口要求实现的方法functioncurrent()
{return$this->_employees[$this->_position];
}
functionkey()
{return$this->_position;
}
functionnext()
{$this->_position++;
}
functionrewind()
{$this->_position = 0;
}
functionvalid()
{returnisset($this->_employees[$this->_position]);
}
}
//Employee 类同前//应用:$lsgo = new Department('LSGO实验室');
$e1 = new Employee("小锦");
$e2 = new Employee("小猪");
$lsgo->addEmployee($e1);
$lsgo->addEmployee($e2);
echo"LSGO实验室部员情况:";
//这里其实遍历的$_employeeforeach($lsgoas$val){
echo"部员{$val->getName()}";
}
附加:
假如现在我们想要知道该部门有几个员工,如果是数组的话,一个 count() 函数就 ok 了,那么我们能不能像上面那样把对象当作数组来处理?SPL标准库中提供了 Countable 接口供我们使用:
classDepartmentimplementsIterator,Countable{//前面同上//实现Countable中要求实现的方法functioncount(){return count($this->_employees);
}
}
//应用:echo"员工数量:";
echo count($lsgo);
本博客参考自《深入理解PHP高级技巧、面向对象与核心技术》
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('').text(i)); }; $numbering.fadeIn(1700); }); });