Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing all objects of a certain class

Tags:

oop

php

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 something, particularly if there is a way to do it without the use of arrays.

Any help is appreciated!

like image 492
cc0 Avatar asked Jan 31 '10 19:01

cc0


1 Answers

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.

like image 66
Wim Avatar answered Sep 27 '22 21:09

Wim