title: Get all instances of a class in PHP
body: <p>I would like to get all the instances of an object of a certain class.</p>
  
  <p>For example:</p>
  
  <pre><code>class Foo {
  }
  
  $a = new Foo();
  $b = new Foo();
  
  $instances = get_instances_of_class('Foo');
  </code></pre>
  
  <p><code>$instances</code> should be either <code>array($a, $b)</code> or <code>array($b, $a)</code> (order does not matter).</p>
  
  <p>A plus is if the function would return instances which have a superclass of the requested class, though this isn't necessary.</p>
  
  <p>One method I can think of is using a static class member variable which holds an array of instances.  In the class's constructor and destructor, I would add or remove <code>$this</code> from the array.  This is rather troublesome and error-prone if I have to do it on many classes.</p>