title: php container class: why does everyone use the more complicated method?
body: <p>When I find scripts for php or look at php frameworks I see a "registry class" or a "container class" which often holds variables or other objects utilizing the __get magic method.</p>
  
  <p>Here is a oversimplified example of what I mean:</p>
  
  <p><strong>example 1:</strong></p>
  
  <pre><code>class container {
   private $objects;
   public function __get($class){
    if(isset($this-&gt;objects[$class])){
     return $this-&gt;objects[$class];
    }
    return $this-&gt;objects[$class] = new $class();
   }
  }
  </code></pre>
  
  <p>the above example will have more functions to it when creating the class instead of just calling it but for my example it should be enough.
  "example 1" is how I mostly see it in scripts downloaded from the internet, it maintains a single class instance, now what I'm wondering is that wouldn't this example do the same thing and be more efficient:</p>
  
  <p><strong>example 2:</strong></p>
  
  <pre><code>class simplecontainer {
   public function __get($class){
    return $this-&gt;$class = new $class();
   }
  }
  </code></pre>
  
  <p>But I never see "example 2" in other peoples scripts which makes me think twice before even considering to use it.</p>
  
  <p>I tested container vs simplecontainer using several classes that they would contain and re-use around 100000 times and "example 1" does it in 0.75seconds on my local machine, and "example 2" does it in 0.29seconds.</p>
  
  <p>which should I use in my scripts? example 1 or example 2? and why?</p>