获取对象 php 内对象的变量名


Get variable name of object inside the object php

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

伪代码:

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

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

我不知道

为什么,但你来了。

<?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

我创建了这段代码,试图回答如何在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();

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

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

$my_instance = new test("my_instance");