Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm wondering if this was possible and I could not find a way to do it so I ask. How can I get the name of the variable where in a instance of a class is present.

Pseudo code:

class test{

    public $my_var_name = '';

    function __construct(){

        //the object says: Humm I am wondering what's the variable name I am stored in?
        $this->my_var_name = get_varname_of_current_object();

    }

}

$instance1 = new test();
$instance2 = new test();
$boeh = new test();

echo $instance1->my_var_name . ' ';
echo $instance2->my_var_name . ' ';
echo $boeh->my_var_name . ' ';

The output would be like:

instance1 instance2 boeh

Why! Well I just wanna know its possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

I have no idea why, but here you go.

<?php
class Foo {
    public function getAssignedVariable() {

        $hash = function($object) {
            return spl_object_hash($object);
        };

        $self = $hash($this);

        foreach ($GLOBALS as $key => $value) {
            if ($value instanceof Foo && $self == $hash($value)) {
                return $key;
            }
        }
    }
}

$a = new Foo;
$b = new Foo;

echo '$' . $a->getAssignedVariable(), PHP_EOL;  // $a
echo '$' . $b->getAssignedVariable(), PHP_EOL;  // $b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...