0

How to get a caller method name in an class constructor, get_called_class() gives me the name of an extended class which was instantiated but how can I get the name of a method which was called in that class? I need this for a production state so debug_backtrace() is not a good solution.

4 Answers 4

1

Why do you need this? If you have any consideration for other coders on the project and standards, find a solution which does not require the constructor to know about how it was called. If all other solutions fail, define a static factory method and make the constructor private for more control over instantiation.

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like there is not way to get it without debug_backtrace(). Still you can create your our function for this. Example from manual:

function get_caller_method() 
{ 
    $traces = debug_backtrace(); 

    if (isset($traces[2])) 
    { 
        return $traces[2]['function']; 
    } 

    return null; 
} 

Comments

0

There is no automatic way of doing this other than the slow/ugly debug_backtrace, or passing the name as an argument to the constructor.... but you shouldn't really be building these kinds of dependencies into your classes.

Comments

0

If you don't want to use the debug_backtrace() function, you can also throw and catch an exception, to get a backtrace.

But that's also ugly... Anyway:

try
{
    throw new Exception();
}
catch( Exception $e )
{
    print_r( $e->getTrace() );
}

I don't know why you need the caller. Maybe you can fix this by using a different logic.
It should be better than getting a backtrace...

EDIT

The exception does not need to be thrown. Sorry for that part.
So you can simply use:

$e = new Exception();
print_r( $e->getTrace() );

But once again, you shouldn't need to use this!

2 Comments

Cant use simply use: $e = new Exception; $e->getTrace()? Is it required to be thrown, to get the trace?
I thought so, but I've just tested, and no, it does not need to be thrown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.