views:

156

answers:

3

is there a way to find out, where a function in PHP was called from? example:

function epic()
{
  fail();
}

function fail()
{
  //at this point, how do i know, that epic() has called this function?
}
+1  A: 

Use the debug_backtrace function: http://php.net/manual/en/function.debug-backtrace.php

Yehonatan
A: 

Use debug_backtrace():

function fail()
{
    $backtrace = debug_backtrace();

    // Here, $backtrace[0] points to fail(), so we'll look in $backtrace[1] instead
    if (isset($backtrace[1]['function']) && $backtrace[1]['function'] == 'epic')
    {
        // Called by epic()...
    }
}
BoltClock
That definitely does what you want. But beware `debug_backtrace()` is an expensive call. Don't get in the habit of using it to determine call-chains. If you want to "protect" those functions, check out OOP and protected methods.
ircmaxell
thanks a lot to all of you!
pol_b
+4  A: 

You can use debug_backtrace().

Example:

<?php

function epic( $a, $b )
{
    fail( $a . ' ' . $b );
}

function fail( $string )
{
    $backtrace = debug_backtrace();

    print_r( $backtrace );
}

epic( 'Hello', 'World' );

Output:

Array
(
    [0] => Array
        (
            [file] => /Users/romac/Desktop/test.php
            [line] => 5
            [function] => fail
            [args] => Array
                (
                    [0] => Hello World
                )

        )

    [1] => Array
        (
            [file] => /Users/romac/Desktop/test.php
            [line] => 15
            [function] => epic
            [args] => Array
                (
                    [0] => Hello
                    [1] => World
                )

        )

)
romac