2

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 !

1
  • It's not generally possible to do so. Why do you (think you) need this? Commented Feb 29, 2012 at 9:44

1 Answer 1

5

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;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Well, you could do some debug_backtraceing and introspection and hacking... But there's really no reason to do so, so +1. :)
I've just added some infos, please see if you could suggest something else. Thanks !
In my opinion you can pass animal's name to the constructor and skip the array keys. Then you can work with foreach and just call method getName() on the animals objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.