I found a great example in Soen which allows to somehow use inform what scope the custom method was called.
It will be necessary to use the $trace = debug_backtrace(FALSE);
that lets you know where your method was called.
foo.php should look something like:
<?php
function foo() {
//Pega o escopo de quem chamou foo();
$trace = debug_backtrace(false);
$message = 'Olá mundo! ' .
sprintf('in %s on line %d Triggered', $trace[0]['file'], $trace[0]['line']);
$trace = NULL;
trigger_error($message, E_USER_NOTICE);
}
When running index.php:
<?php
require 'foo.php';
//Chamando
foo();
echo '<pre>';
print_r(error_get_last());
echo '</pre>';
You will get the error on the screen and can still use error_get_last()
(This will vary from what type of error you are using in trigger_error
or if you’re going to capture with set_handler_error
), the exit will be something like this:
Notice: Hello world! in /path/index.php on line 5 Triggered in /path/foo.php online 11
Array
(
[type] => 1024
[message] => Hello world! in /path/index.php on line 5 Triggered
[file] => /path/foo.php
[line] => 11
)
Note that in the error_get_last
the line the reported file is from foo.php, but you can parse in message
if you need.
The idea of creating a custom error like this is to be able to create own functions and if there is any fault the script will be able to inform exactly where the method was executed, for example:
function dividir($a, $b) {
$err = NULL;
if (false === is_numeric($a)) {
$err = 'Primeiro argumento é invalido';
} else if (false === is_numeric($b)) {
$err = 'Segundo argumento é invalido';
} else if ($b == 0) {
$err = 'Não pode dividir por zero';
}
if ($err) {
$trace = debug_backtrace(false);
$message = $err .
sprintf('in %s on line %d Triggered', $trace[0]['file'], $trace[0]['line']);
$trace = NULL;
trigger_error($message, E_USER_NOTICE);
return NULL;
}
return $a / $b;
}
In this case we have 3 possible errors, so if we use the method like this in index.php:
<?php
require 'foo.php';
echo dividir(10, 0);
We’ll have the following mistake:
Notice: Can’t divide by zero in index.php on line 4 Triggered in foo.php on line 20
Some details in this other debug_backtrace answer: /a/78168/3635
Before giving a negative vote, understand the community model, read: http://answall.com/help/self-answer and http://blog.stackoverflow.com/2012/05/encyclopedia-stack-exchange and if you have any other reason to downvote please justify.
– Guilherme Nascimento