NYCPHP Meetup

NYPHP.org

[nycphp-talk] getting an object's variable name

Scott Mattocks scott at crisscott.com
Tue Mar 14 12:39:52 EST 2006


Jeff Knight wrote:
> I actually have a question for y'all (all'y'all? y'all all?). Is it
> possible to get the variable name used by an object from that object?
> If I had
> 
> class Example {	
> 	function varName() {
> 		// what goes here?
> 	}
> }
> 
> $nyphp = new Example() ; $txphp = new Example();
> 
> I want $nyphp->varName() to return the string 'nyphp', and
> $txphp->varName() to return 'txphp'

Here is a completely dirty hack that probably won't work quite right and 
probably takes way to long:

function varName()
{
     foreach (get_declared_vars() as $key => $value) {
         if ($value === $this) {
             return $key;
         }
     }
}

Other than this, I don't see how it can be done.

-- 
Scott Mattocks
http://www.crisscott.com



More information about the talk mailing list