tags:

views:

70

answers:

4

Is there a way for a class called inside another to know the name of the outer class?

Example:

class A{
  // need to get the name of B
  // some stuff
}

class B{
  $var = new A;
}

get_parent_class() qon't do the work since B is not a child of A.

Any suggestions?

Edit: Sorry everyone I had to change the question. What I wanted to ask is can class A know the name of the class in which it is being called. Again sorry for idiotic first question.

+2  A: 

You want get_class()

get_class — Returns the name of the class of an object

edit As gordon said this is not possible. You might be able to parse the call stack to see what class called the one you are in, but I wouldn't do it.

Byron Whitlock
+6  A: 

Nope, it's impossible.

Well, almost. You could hack your way to the calling class from debug_backtrace or apd_callstack, but that is rather inefficient and slow. Xdebug has a number of functions that could help you achieve this too, but all of this is nothing you want in production code.

The easiest way would be to pass the instance of B to A, e.g.

class A {
    protected $callerInstance;
    protected $callerClassName
    public function __construct($caller) {
        $this->callerInstance = $caller;
        $this->callerClassName = get_class($caller);
    }
}
Gordon
I completely agree with you. Not understanding why people is voting this down.
Roberto Aloi
@Gordon you're right, we all got it wrong. +1.
Pekka
+1 for reading the question right (and having the correct answer ofc)
Yacoby
again thanks for pointing out the mistake in the question. :)
Sinan
I deserve a Badge for this :D
Gordon
A: 
get_class($var)
Amber
+1  A: 

It's possible if you pass the name of class B to the class A constructor. That would require a modification in class A (and all classes you need this for). Hackish, but does what you need.

class A{
  function __construct($caller){
     echo $caller; // will echo B, C and D respectively
  }
}

class B{
   $var = new A(get_class($this));
}

class C{
   $var = new A(get_class($this));
}

class D{
   $var = new A(get_class($this));
}
code_burgar