6

i have to list objects that are instance of a class by refrence

class Foo {}
class Foo1 {}
$obj1 = new Foo;
$obj2 = new Foo;
$obj32 = new Foo1;

i need a solution to get all objects that are instance of Foo class do you know how to do that ?

Omid
  • 4,575
  • 9
  • 43
  • 74
  • are you dynamically creating them? – JohnP Jun 27 '11 at 11:48
  • 1
    What does all mean? In the global or in the local variable space or even both? Which variable names do you use? Can you extend the class to make it recordkeeping of instances? – hakre Jun 27 '11 at 11:48
  • by all instances of Foo, do you also mean all instances of subclasses? If there was a class Foo2 extends Foo {} for example, would you want all the Foo2 objects as well? – GordonM Jun 27 '11 at 11:49
  • @GordonM: no, i need just object of Foo. that's not important that Foo2 extends Foo – Omid Jun 27 '11 at 11:51
  • @hakre: all in the both local and global scope – Omid Jun 27 '11 at 11:51
  • @Omid Amraei: See my answer, it provides such an array for `Foo`. If you need the extended classes as well, take care that the constructor is called. – hakre Jun 27 '11 at 11:53
  • possible duplicate of [Get all instances of a class in PHP](http://stackoverflow.com/questions/475569/get-all-instances-of-a-class-in-php) – hakre Jun 27 '11 at 11:57

2 Answers2

14

A solution to get all instances of a class is to keep records of instantiated classes when you create them:

class Foo
{
  static $instances=array();
  public function __construct() {
    Foo::$instances[] = $this;
  }
}

Now the globally accessible array Foo::$instances will contain all instances of that class. Your question was a bit broad so I can not exactly say if this is what you're looking for. If not, it hopefully helps to make it more clear what you're looking for.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • wouldn't this prevent GC of removing this object ? – dfens Jun 05 '18 at 17:07
  • Not only GC, these objects are not destructed even, so GC won't even kick in. So you need to clean yourself (`Foo::$instances = [];`). – hakre Jun 05 '18 at 17:17
2

See this answer Get all instances of a class in PHP has worked for me to do this in the past.

Community
  • 1
  • 1
Brian
  • 8,418
  • 2
  • 25
  • 32