Advertisement
dragonbe

autoloading

Nov 14th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. //file: Classes/Cupboard.php
  3. class Cupboard
  4. {
  5.     protected $_items;
  6.    
  7.     public function addItem($item)
  8.     {
  9.         $this->_items[] = $item;
  10.         return $this;
  11.     }
  12.     public function removeItem($item)
  13.     {
  14.         $key = array_search($item, $this->_items);
  15.         unset ($this->_items[$key]);
  16.         return $this;
  17.     }
  18.     public function listItems()
  19.     {
  20.         return implode(', ', $this->_items);
  21.     }
  22.    
  23. }
  24.        
  25.  
  26.  
  27. <?php
  28. // file: Run.php
  29. function __autoload($class)
  30. {
  31.     $path = dirname(__FILE__) . '/Classes';
  32.     $classFile = $path . '/' . ucfirst(strtolower($class)) . '.php';
  33.     if (!file_exists($classFile)) {
  34.         throw new InvalidArgumentException('Non-existing class provided');
  35.     }
  36.     require_once $classFile;
  37. }
  38. $cb = new Cupboard();
  39. echo $cb->addItem('plate')
  40.         ->addItem('cup')
  41.         ->addItem('spoon')
  42.         ->addItem('fork')
  43.         ->removeItem('spoon')
  44.         ->listItems() . PHP_EOL;
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement