欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP的Collection集合类

程序员文章站 2023-12-24 13:13:15
...
  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

上一篇:

下一篇: