0

Possible Duplicate:
How to get name of calling function/method in PHP?

So in PHP I'm trying to build a custom error handler class. It's pretty simple: I give it a code number and it gives back a formatted error message which I can use to send to mobile devices.

So it looks like this now:

class Errorhandler {
   private $errors = array(
       //here be error codes and messages
       100 => 'Missing input or parameter!'
  );

   public function __construct($code = 100){
        //return formatted output
   }
}

So I'd use the class above like:

public function someFunction(){
    //some conditions met, then throw an error
    $handler = new ErrorHandler();
    $this->response = $handler;        
}

So I'd need the parent function's name (someFunction) in my Errorhandler class so I can return it with the formatted error message. On a side note: I don't want to use parameters for this, too much writing there.

Community
  • 1
  • 1
peaks
  • 167
  • 2
  • 11

3 Answers3

2

__FUNCTION__

It's magic. See more here: http://www.php.net/manual/en/language.constants.predefined.php

As for actually getting it in your ErrorHandler class, you'd have to pass it to the constructor. PHP isn't that magical.

user428517
  • 4,132
  • 1
  • 22
  • 39
  • 1
    No, he meant the function that actually calls `__FUNCTION__`... – Ron Oct 24 '12 at 20:06
  • Wouldn't it be returning my custom errorhandler class's __construct() name? – peaks Oct 24 '12 at 20:08
  • `$handler = new ErrorHandler(__FUNCTION__);` ? Isn't that what you want? Then grab the function name in the `ErrorHandler` constructor and assign it to a class variable. Either that or use `debug_backtrace()` within the class itself. – user428517 Oct 24 '12 at 20:10
  • Sadly no, because with this, I have to type in `__FUNCTION__` every time which is boring if you know what I mean. – peaks Oct 24 '12 at 20:12
  • so declare a global reference to it called `F` or something and pass that. Or just use `debug_backtrace()` which would be less messy. – user428517 Oct 24 '12 at 20:14
0

You can use debug_backtrace() to get the function that have called your function.

debug_backtrace() returns the current call stack.

Ron
  • 1,336
  • 12
  • 20
0

You can parse debug_backtrace() function output. It returns associative array of all calls to the very top (http://php.net/manual/en/function.debug-backtrace.php)

Also notice that fatal error will interrupt normal script excution and to catch it you need to call error handler from callback registered with register_shutdown_function() (http://php.net/manual/ru/function.register-shutdown-function.php)