David Tran
David Tran

Reputation: 10646

PHP get variable's name of class instance?

I'm new to PHP so this question seems stupid, but suppose I'm assigning variable ABC with value to be a new object of class XYZ, then how could I get the name "ABC" inside XYZ's class definition ?

$ABC = new XYZ;
$ABC->echoInstanceName(); //--I wish this line could echo out : ABC

Is this easier when the instance is assigned to an array's element ?

$ABC = array('myElem'=>new XYZ);
$ABC['myElem']->echoInstanceName(); //--I wish this line could echo out : ABC

All suggestions appreciated !


More infos : I'm doing kind of thing: build a system of animals.

Started with class nativeAnimal & extended to Monkey, Elephant, Fish...etc. And in runtime, I create a 2-tiers array that each array's element is an instance of type Monkey, Elephant, or Fish...

I want the array's key is the animal's name. And inside the class Monkey, I want a function to echo the Monkey's name. Of course I can pass the array's key to the instance somehow, but I want to avoid typing it twice. (That can lead to error(s) later when I change just one name)

Is this so impossible ? Or could you please suggest a better pattern ? Thanks !

Upvotes: 2

Views: 4615

Answers (1)

hsz
hsz

Reputation: 152304

You cannot do this. If you want to pass ABC value to the XYZ class, do it with an extra argument in constructor:

$ABC = new XYZ('ABC');

There is no other way to inform class about variable that it was assigned to.

Example XYZ class:

class XYZ {
  protected $name;
  public __construct($name) {
    $this->name = $name;
  }

  public echoInstanceName() {
    echo $name;
  }

  public getName() {
    return $this->name;
  }
}

Upvotes: 5

Related Questions