Tom Brunoli
Tom Brunoli

Reputation: 3476

Getting the variable name of an instantiated class in PHP

Is it possible to get the variable name used to reference an instantiated class from within the class? here's an example of what i mean:

class Test {
    function getName(){
    //some code here to get the name '$test1' in this example
    }
}

$test1 = new Test

It's not a must for this to be possible, but it'd help for a project i'm working on.

Upvotes: 1

Views: 322

Answers (2)

too much php
too much php

Reputation: 91078

You could most likely do it using debug_backtrace(), however this sort of hack is extremely bad practice.

Upvotes: 0

Lotus Notes
Lotus Notes

Reputation: 6363

You can use the variable $this to reference the object from within itself.

If you want to find the actual name of the variable $test1, it's going to be more difficult (maybe impossible, since the class has no way to know how it is being used in the global scope). But probably not worth it. Most of the time I've seen questions like that asked, people suggest that there's a design flaw and the application should depend on something other than variable names.

Upvotes: 2

Related Questions