Get variable name of object inside the object php

2020-02-14 20:29发布

问题:

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.

回答1:

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


回答2:

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();


回答3:

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");


标签: php oop object