2

我想知道这是否可能,我找不到办法,所以我问。如何获取类实例中存在的变量的名称。

伪代码:

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 . ' ';

输出如下:

instance1 instance2 boeh

为什么!好吧,我只是想知道它的可能。

4

3 回答 3

7

我不知道为什么,但给你。

<?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
于 2013-10-02T11:53:47.027 回答
3

我创建了这段代码,试图回答如何在 PHP 的类中获取初始化变量的名称

但它已经关闭并引用了这个问题,

只是另一个易于阅读的变体,我希望我没有破坏任何基本概念哦 php 开发:

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();
于 2015-01-09T01:33:19.177 回答
0

我找不到这样做的充分理由。

无论如何,您可以做的一种方法(但就我所能想象的而言,它再次没有用)这是通过将实例名称作为构造函数的参数传递,如下所示:

$my_instance = new test("my_instance");
于 2013-10-02T11:49:49.027 回答