2013-10-02 44 views
2

我想知道這是否可能,我找不到一種方法來做到這一點,所以我問。我如何獲得在類的實例中存在的變量的名稱。獲取對象內部變量的名稱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 

爲什麼!那麼我只是想知道它可能。

回答

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 
+1

好它的工作原理,我可能永遠不會使用它,但至少你回答了這個問題。 – botenvouwer

0

我找不到一個很好的理由來做到這一點。

不管怎麼說,你可以做(​​但同樣它已經沒有用了,只要我能想象)的一種方式,這是通過將實例名稱作爲構造函數的參數,就像這樣:

$my_instance = new test("my_instance"); 
3

我創造了這個代碼試圖回答How to get name of a initializer variable inside a class in 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();