Yusuf Y.
Yusuf Y.

Reputation: 84

How do I get the function that runs the function?

I'm using an error log function, and I want to include the function where the error occurred during the error log. Is there a way to write the function instead of writing the function every time?

<?php 

$a = null;

exampleFunction($a);

function exampleFunction($variable){

  if(is_null($variable)){

    errorLog("variable is null. ");

  }

}

function errorLog($text){

 error_log($text, 3, ".testLog");

}

?>

__FUNCTION__ is not solution. If I use __FUNCTION__ I get "errorLog". I want to know the name of the function that is running errorLog.

For example ;

function errorLog($text){

  error_log($text.' Function : '.$functionName, 3, ".testLog");

}

Upvotes: 1

Views: 37

Answers (1)

Progrock
Progrock

Reputation: 7485

You can use debug_backtrace to get a list of the function call stack:

<?php
function foo()
{
    bar();
}

function bar()
{
    echo debug_backtrace()[1]['function'];
}

foo();

Output:

foo

Upvotes: 3

Related Questions