kaiser
kaiser

Reputation: 22333

How to get class/function/line name in a function outside a class

Example:

class myExample
{
    public function example_fn()
    {
        $example_val = $this->some_fn();
        _debug( $example_val, _get_position() );
    }
}

/**
 * Debug function
 */
function _debug( $input, $position )
{
    $output  = '<strong>Inside: '.$position.'</strong><br />';
    $output .= '<pre>';
    $output .= print_r( var_export( $input, true ), true );
    $output .= '</pre>';

    return print $output;
}

/**
 * Position function
 */
function _get_position()
{
    return 'Class: '.__CLASS__.' // Function: '.__FUNCTION__.' // Line: '.__LINE__;
}

Question:

With the current setup, the output returns the values of the position where the _get_position() function was defined. Can I somehow get the Class/function/line from where the _get_position() function was called?

Thank you!

Upvotes: 0

Views: 77

Answers (2)

Arvin
Arvin

Reputation: 2282

You got to use debug_backtrace for that:

function _get_position()
{
    $stack = debug_backtrace();
    return 'Class: '.$stack[1]['class'].' // Function: '.$stack[1]['function'].' // Line: '.$stack[0]['line'];
}

Upvotes: 1

Related Questions