tags:

views:

34

answers:

3

In PHP, is it possible to get the file name of the script that instantiated an object?

For example I have a script called file.php that creates a new instance of class Class. The class has an Error object that, when triggered, returns some error information. I would like to show that file.php triggered the error.

+3  A: 

The function debug_backtrace() may be of use? It shows the execution flow from bottom to top.

Kai Sellgren
That will only work if the error is triggered within the constructor of Class, no? Maybe that's what he want, I don't know.
Savageman
Thanks, exactly what I was looking for!
Calvin L
@Savageman, yeah, that's where it's being triggered, but that's ood to know too.
Calvin L
+1  A: 

Any chance that error_get_last's returned array satisfies your need? The function 'returns an associative array describing the last error with keys "type", "message", "file" and "line". Returns NULL if there hasn't been an error yet. '

http://www.php.net/manual/en/function.error-get-last.php

Jeba Singh Emmanuel
It's a custom error reporter, not for PHP errors, but thanks for that function too.
Calvin L
+2  A: 

As Kai Sellgren said, the *debug_backtrace()* function can be used. You can also throw and catch an exception to get a backtrace.

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

As getting a backtrace can take some time, you should benchmark both solutions to see which is the fastest.

And by the way, shoudn't your error object be a subclass of Exception? That's the reason why exceptions exists...

Macmade