How to get called function name in __construct without debug_backtrace
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 th开发者_运维问答e 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.
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.
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;
}
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.
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!
精彩评论