简体   繁体   中英

Get name function in PHP

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 ?

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.

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'];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM