Does PHP show the names of all declared classes?

Let's 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 can I make an echo of all the names of created objects (and, if possible, their corresponding class) so that it echoes (possibly in an array) "hello1 => hello, hello2 => hello, hello4 => hello".

If this is not possible, is it possible to specify an instance name from a class, something like echo instance_name ($ this); I would get "hello1". Thanks.

+3
source share
1 answer

You can call get_defined_varsto get an array of all the objects present, and then use get_classto get the class names for each of them (code not tested, but it should work):

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

FYI, , " ", "".

. , :

$hello1 = $hello2 = new hello();

, instance_name, 'hello1' 'hello2'?

+9

Source: https://habr.com/ru/post/1707632/


All Articles