Styphon
Styphon

Reputation: 10447

PHP Is it possible to identify the name of the variable containing the object?

In PHP is it possible to identify the name of the variable containing the object? For example:

class Foo {

    public function IdentifyContainer() {
        //PHP to identify variable containing Foo.
    }

}

$bar = new Foo();
echo $bar->IdentifyContainer(); // This should echo "bar";

I have no idea if this can be done or not, but it would really help me if it can as I have 4 instances of the same class being called on a single page load and I'm trying to identify them all.

EDIT

I should have originally mentioned this is purely for debugging. debug_backtrace worked for me. Thanks to everyone who suggested it :).

Upvotes: 2

Views: 90

Answers (2)

Philipp
Philipp

Reputation: 15629

There's no easy way to do this.

But it's theoretically possible(which doesn't mean, you should do this..). You could use debug_backtrace to get the callstack to get the file and line number of the calling script. With this information, you could open the php file(fopen, etc..) to get the line content and with regular expressions, you could get the name of the var, calling your method.

Proove of concept:

function getCallingVarName() {
    $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
    array_shift($trace);
    $call = $trace[0];
    $file = $call['file'];
    $fnc = $call['function'];
    $lines = file($file);
    $line = $lines[$call['line'] - 1];
    if (preg_match('~\$([^-]+)->' . $fnc . '\(~', $line, $m)) {
        return $m[1];
    }
}

So, it's possible - but some reasons to don't do this:

  • this is slow!
  • this is unsafe (someone could put multiple statements in the same line of the php file)

some reasons you shoul'd do this at all:

$a = new A();
$b = $a;

so you have multiple vars, which point to the same reference, but what you want your code to behave different if you call $a->test() or $b->test() - sound very, very error prone..

Upvotes: 2

deceze
deceze

Reputation: 522342

No, not in any sane way. There's also no good reason to do this whatsoever. No, even if you think you have a good reason, you don't. Since it's perfectly possible to assign an object to several variables at once, there's no intrinsic link between an object (or any value for that matter) and the variable it's assigned to. A variable is not a "container", a variable is a placeholder in an algorithm that lets you refer to changing (variable) values.

Upvotes: 3

Related Questions