首頁  >  文章  >  後端開發  >  PHP的Collection集合類

PHP的Collection集合類

WBOY
WBOY原創
2016-07-25 08:44:181482瀏覽
  1. header("Content-type:text/html; charset=utf-8");
  2. class Collection{
  3. private $_members=array();
  4. private $_onload;
  5. private $_isLoaded=false;
  6. public function startLoad(){
  7. $this->_checkCallback();
  8. }
  9. public function addItem($obj,$key=NULL){
  10. $this->_checkCallback();
  11. if($key){
  12. if(isset($this->_members[$key])){
  13. throw new Exception("Key \"$key\" already in use!");
  14. }else{
  15. $this->_members[$key]=$obj;
  16. }
  17. }else{
  18. $this->_members[]=$obj;
  19. }
  20. }
  21. public function removeItem($key){
  22. $this->_checkCallback();
  23. if(isset($this->_members[$key])){
  24. unset($this->_members[$key]);
  25. }else{
  26. throw new Exception("Invalid key \"$key\"!");
  27. }
  28. }
  29. public function getItem($key){
  30. $this->_checkCallback();
  31. if(isset($this->_members[$key])){
  32. return $this->_members[$key];
  33. }else{
  34. throw new Exception("Invalid key \"$key\"!");
  35. }
  36. }
  37. public function keys(){
  38. $this->_checkCallback();
  39. return array_keys($this->_members);
  40. }
  41. public function length(){
  42. $this->_checkCallback();
  43. return sizeof($this->_members);
  44. }
  45. public function exists($key){
  46. $this->_checkCallback();
  47. return (isset($this->_members[$key]));
  48. }
  49. public function setLoadCallback($functionName,$objOrClass=NULL){
  50. if($objOrClass){
  51. $callback=array($objOrClass,$functionName);
  52. }else{
  53. $callback=$functionName;
  54. }
  55. if(!is_callable($callback)){
  56. /*throw new Exception("$callableName is not callable"."as a parameter to oonload");*/
  57. echo "$callback is not callable
    ";
  58. return false;
  59. }
  60. $this->_onload=$callback;
  61. }
  62. private function _checkCallback(){
  63. if(isset($this->_onload)&&!$this->_isLoaded){
  64. $this->_isLoaded=true;
  65. call_user_func($this->_onload,$this);
  66. }
  67. }
  68. }
复制代码

PHP,集合


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn