2

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.

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Good it works, I probably never use it but at least you answered the question.
3

I created this code trying to answer for How to get name of a initializer variable inside a class in PHP

But it is already closed and referenced to this question,

just another variant easy to read, and I hope I didn't break any basic concept oh php development:

class Example
{
   public function someMethod()
   {

    $vars = $GLOBALS;
    $vname = FALSE;
    $ref = &$this;
    foreach($vars as $key => $val) {
        if( ($val) === ($ref)) {
            $vname = $key;
            break;
        } 
    }

    return $vname;
   }

}

$abc= new Example;
$def= new Example;
echo $abc->someMethod(); 
echo $def->someMethod();

Comments

0

I can't find a good reason to do that.

Anyways, one way you can do (but again it has no use as far as i can imagine) this is by passing the instance name as a constructor's parameter, like this:

$my_instance = new test("my_instance");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.