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 !
You cannot do this. If you want to pass
ABCvalue to theXYZclass, do it with an extra argument in constructor:There is no other way to inform class about variable that it was assigned to.
Example
XYZclass: