Listing all objects of a certain class
Ok my problem is as follows;
I have a class that describes a pet with this constructor;
public function __construct($name, $type, $age)
So what I want to do is make a number of pet 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 of going about it? I know how to iterate through an object's variables, but my main concern is how to iterate through all objects of a certain class. I would love it if someone could show me a code example of somet开发者_StackOverflowhing, particularly if there is a way to do it without the use of arrays.
Any help is appreciated!
You could, in the class constructor, append $this
to a static array that keeps all the 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
.
Normally you would expect to have some way of tracking the instances you've created, maybe in an array or some kind of containing class.
But for the sake of argument, you could check all the variables in the current scope with get_defined_vars(), recursively searching any arrays or objects 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);
I guess it depends on your structure, but I´d have another object / class that contains all generated pet objects, so I would loop through that.
Well, you could make a custom create option and use static variables to store an instance of each created class
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;
}
i would make a foreach loop
foreach($myobject as $key => $pent)
{
echo $key;
echo $pent;
}
精彩评论