0

I have some classes:

class A
{
   private $_method;
   public function __construct()
   {
       $this->_method = new B();
   }
   public function demo()
   {
     $this->_method->getNameFnc();
   }
}

class B
{
   public function getNameFnc()
   {
     echo __METHOD__;
   }
}

I'm trying to get the function name of a class B class, but I want the function getNameFnc to return 'demo'. How do I get the name 'demo' in function getNameFnc of class B?

adamdunson
  • 2,635
  • 1
  • 23
  • 27
Dean
  • 415
  • 1
  • 5
  • 15

3 Answers3

1

Well, if you really want to do this without passing a parameter*, you may use debug_backtrace():

→ Ideone.com

public function getNameFnc()
{
  $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
  echo $backtrace[1]['function'];
}

* this would be the recommended way although one should never need to know which function has been previously called. If your application relies on that fact, you have got a major design flaw.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • 2
    +1 for the major design flaw. debug_backtrace should only be used for debugging purposes and not for application workflow. – ILikeTacos Jan 13 '14 at 16:53
1

You will need to use debug_backtrace to get that information.

I haven't tested the code below but I think this should give you the information you want:

$callers = debug_backtrace();
echo $callers[1]['function'];
ILikeTacos
  • 17,464
  • 20
  • 58
  • 88
  • 1
    It has to be `$callers[0]`, and you should also limit the backtrace using the second parameter. – ComFreek Jan 13 '14 at 16:51
  • Sorry for the wrong information in my last comment. Of course it is `1` and not `0`. Even my demo link was buggy, I can't believe that nobody corrected me ;) – ComFreek Jan 13 '14 at 18:23
  • haha no problem, I didn't have the time to test neither your code nor mine, so I just assumed yours was correct. Thanks for letting me know! – ILikeTacos Jan 13 '14 at 18:39
0

Why not pass it?

class A
{
   private $_method;
   public function __construct()
   {
       $this->_method = new B();
   }
   public function demo()
   {
     $this->_method->getNameFnc(__METHOD__);
   }
}

class B
{
   public function getNameFnc($method)
   {
     echo $method;
   }
}

Or use __FUNCTION__ if you don't want the class name.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 1
    You have basically just created a wrapper for the `echo` function. It works, but is completely pointless. – Drumbeg Jan 13 '14 at 16:59