当前位置:Gxlcms > PHP教程 > PHP的Collection集合类

PHP的Collection集合类

时间:2021-07-01 10:21:17 帮助过:4人阅读

  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, Collection

人气教程排行