List of all objects of a particular class

Ok, my problem is this:

I have a class describing a pet with this constructor;

public function __construct($name, $type, $age) 

So what I want to do is make some home objects, then I want to print all the attributes of all the objects of this class so that it looks something like this

What is the best way to do this? I know how to iterate through object variables, but my main problem is how to iterate over all objects of a particular class. I would love it if someone could show me some sample code, especially if there is a way to do this without using arrays.

Any help is appreciated!

+6
oop php
source share
5 answers

Usually, you expect to have some way of tracking the instances you created, possibly in an array or some kind of class.

But for the sake of argument, you can check all the variables in the current scope with get_defined_vars () , recursively search for any arrays or objects that you find with something like this:

 function findInstancesOf($classname, $vars) { foreach($vars as $name=>$var) { if (is_a($var, classname)) { //dump it here echo "$name is a $classname<br>"; } elseif(is_array($var)) { //recursively search array findInstancesOf($classname, $var); } elseif(is_object($var)) { //recursively search object members $members=get_object_var($var); findInstancesOf($classname, $members); } } } $vars = get_defined_vars(); findInstancesOf('MyPetClass', $vars); 
+1
source share

In the class constructor, you can add $this to a static array that will save all elements of this type:

 class Pet { public static $allPets = array(); function __construct($name, $type, $age) { self::$allPets[] = $this; // more construction } } 

Your list of all Pet objects is now in Pet::$allPets .

+5
source share

I assume this depends on your structure, but I will have another object / class containing all the generated animal objects, so I would go through this.

+1
source share

Well, you can create a custom create option and use static variables to store an instance of each class created

 Class Pet { public static $pets = array(); public static create($name, $type, $age) { $pet = new Pet($name, $type, $age); self::$pets[] = $pet; return $pet; } } Pet::createPet("test", "test", 42); Pet::createPet("test", "test", 42); Pet::createPet("test", "test", 42); foreach(Pet::$pets as $pet) { echo $pet->name; } 
+1
source share

I would do a foreach loop

 foreach($myobject as $key => $pent) { echo $key; echo $pent; } 
+1
source share

All Articles