1

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.

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.