views:

263

answers:

1

Lets say I have this code:

<?php
class hello {
    var $greeting = "hello";
    function hello(){
        echo $this->greeting;
        return;
    }
}

$hello1 = new hello;
$hello2 = new hello;
$hello4 = new hello;
?>

How do I get it to echo all the names of instantiated objects (and if possible their respective class), so that it echos (possibly in an array) "hello1 => hello, hello2 => hello, hello4 => hello".

If this is not possible, is there any way to tell the name of the instance from within the class, something like echo instance_name($this); would get me "hello1". Thanks.

+8  A: 

You could call get_defined_vars to get an array of all the objects present, and then use get_class to get the class names for each one (code not tested, but it should work):

$vars = array();
foreach (get_defined_vars() as $var) {
    $vars[$var] = get_class($var);
}

FYI, what you call a "declared class" is more well known as an "object."

Your second question is not possible. Take, for example:

$hello1 = $hello2 = new hello();

Now, if I call instance_name, should it return 'hello1' or 'hello2'?

Samir Talwar
True.. and combine with is_object if necessary to find which vars are objects
Petrunov
Ok, thanks, I was looking into get_defined_vars(), but I didn't know that objects are also in there, I'll thank a look again, thanks.
Yifan