Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all objects of a particular class

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 ?

like image 593
Omid Avatar asked Jun 27 '11 11:06

Omid


People also ask

How do you print all objects in a class Python?

To print all instances of a class with Python, we can use the gc module. We have the A class and we create 2 instances of it, which we assigned to a1 and a2 . Then we loop through the objects in memory with gc. get_objects with a for loop.

How do you find the object of a class?

Follow the class name with the member-access operator ( . ) and then the member name. You should always access a Shared member of the object directly through the class name. If you have already created an object from the class, you can alternatively access a Shared member through the object's variable.

Is shared by all objects of the class?

A static variable is shared by all instances of a class.


1 Answers

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.

like image 110
hakre Avatar answered Nov 14 '22 21:11

hakre