title: Avoiding $GLOBAL state in PHP with dependancy injection?
body: <p>I have encountered a situation where I would like to avoid using <code>$GLOBAL</code> state, but cannot workout how to do so. I believe Reflection and Dependancy injection could solve this:</p>
  
  <p>Here is a contrived example (Yes I know its a little bent...); Say we have a <code>Calculator</code> class and helper functions that basically replicate its functionality e.g. <code>add, subtract</code>. Now we also want a <code>history</code> of our calculations to be accessible.</p>
  
  <p>How can I use these helper functions without having to manually insert the <code>Calculator</code> as a dependancy?</p>
  
  <pre><code>class Calculator
  {
      private $history = [];
  
      public function add(int $a, int $b): int
      {
          $result = $a + $b;
  
          $this-&gt;history[] = $result;
  
          return $result;
      }
  
      public function subtract(int $a, int $b): int
      {
          $result = $a - $b;
  
          $this-&gt;history[] = $result;
  
          return $result;
      }
  
      public function history(): array
      {
          return $this-&gt;history;
      }
  }
  
  function add(int $a, int $b): int
  {
      $calculator = new Calculator;
      return $calculator-&gt;add($a, $b);
  }
  
  function subtract(int $a, int $b): int
  {
      $calculator = new Calculator;
      return $calculator-&gt;subtract($a, $b);
  }
  
  function history(): array
  {
      $calculator = new Calculator;
      return $calculator-&gt;history(); // Clearly this will be empty
  }
  </code></pre>
  
  <p>See what I mean? Currently calling <code>history()</code> will of course return an empty array...</p>
  
  <p>Of course this would work:</p>
  
  <pre><code>function add(Calculator $calculator, int $a, int $b): int
  {
      return $calculator-&gt;add($a, $b);
  }
  
  function history(Calculator $calculator): array
  {
      return $calculator-&gt;history();
  }
  </code></pre>
  
  <p>Although if i use this as a package its very error prone, labour intensive to manually wire up these dependancies... let alone every time I call a helper function.</p>
  
  <p>Another method that would work is globals:</p>
  
  <pre><code>$GLOBALS['calculator'] = new Calculator;
  
  function add(int $a, int $b): int
  {
      return $GLOBALS['calculator']-&gt;add($a, $b);
  }
  
  function history(): array
  {
      return $GLOBALS['calculator']-&gt;history();
  }
  </code></pre>
  
  <p>Although ... yuk yuk yuk. No thank you.</p>
  
  <p>HELP!</p>