Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

oop - Get variable name of object inside the object php

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...