Advertisement
soywiz

Simulate Anidated Contexts

Apr 5th, 2011
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.40 KB | None | 0 0
  1. <?php
  2.  
  3. error_reporting(E_ALL | E_STRICT);
  4.  
  5. class Context implements ArrayAccess {
  6.     /**
  7.      * @var Context
  8.      */
  9.     protected $parent;
  10.  
  11.     /**
  12.      * @var ArrayObject
  13.      */
  14.     protected $current;
  15.  
  16.     public function __construct($items = array(), Context $parent = NULL) {
  17.         $this->current = new ArrayObject((array)$items);
  18.         $this->parent = $parent;
  19.     }
  20.    
  21.     protected function &getRef($index) {
  22.         $ref = &$this->current[$index];
  23.         if (!isset($ref) && ($this->parent !== NULL)) {
  24.             $ref = &$this->parent->getRef($index);
  25.         }
  26.         return $ref;
  27.     }
  28.  
  29.     public function offsetExists($index) {
  30.         $ref = &$this->getRef($index);
  31.         return isset($ref);
  32.     }
  33.  
  34.     public function &offsetGet($index) {
  35.         return $this->getRef($index);
  36.     }
  37.  
  38.     public function offsetSet($index, $newval) {
  39.         $ref = &$this->getRef($index);
  40.         $ref = $newval;
  41.     }
  42.  
  43.     public function offsetUnset($index) {
  44.         $ref = &$this->getRef($index);
  45.         unset($ref);
  46.     }
  47.  
  48.     public function enter($items = array()) {
  49.         return new static($items, $this);
  50.     }
  51.    
  52.     public function leave() {
  53.         return $this->parent;
  54.     }
  55. }
  56.  
  57. $context = new Context(array('a' => -10, 'b' => -20, 'c' => -30));
  58. $context = $context->enter(array('a' => 10, 'b' => 20));
  59. printf("%d\n", ++$context['a']);
  60. printf("%d\n", ++$context['c']);
  61.  
  62. $context = $context->leave();
  63. printf("%d\n", ++$context['a']);
  64. printf("%d\n", ++$context['c']);
  65.  
  66. $context['c'] = 6;
  67.  
  68. printf("%d\n", $context['c']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement