note 54993 deleted from function.debug-backtrace by cmb
| From: | cmb@php.net | Date: | Sun, 17 Nov 2019 08:32:22 +0000 |
| Subject: | note 54993 deleted from function.debug-backtrace by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213068@lists.php.net to get a copy of this message | ||
Note Submitter: tb
----
I use this for debugging in my object oriented systems. It allows me to output a
debug/error/warning function with exact information about the location that the error was thrown,
which is useful. Check it:
<?php
abstract class Debugger {
/**
* Throw a debug message.
*/
abstract function debug($msg);
/**
* Throw an error message.
*/
abstract function error($msg);
/**
* Throw a warning message.
*/
abstract function warning($msg);
/**
* Wrap a message with information about class, function, file and line
* number and return it.
*/
protected function getMsg($msg) {
$bt = debug_backtrace();
// get class, function called by caller of caller of caller
$class = $bt[2]['class'];
$function = $bt[2]['function'];
// get file, line where call to caller of caller was made
$file = $bt[1]['file'];
$line = $bt[1]['line'];
// build & return the message
return "$class::$function: $msg in $file at $line";
}
}
?>
Implement different debuggers for different scenarios (development, testing, production). Each
debugger extends Debugger; each of its methods (debug/error/warning) calls $this->getMsg($msg) to
get a message with class, function, file, and line information. Then it can either log it, email
it, die with it, etc.
Then, just give each object (perhaps using a common superclass Object) a concrete debugger. Then,
from any object method, do something like:
<?php
class Foo extends Object {
function bar() {
$this->debugger->error("This is an error");
}
}
?>
Which produces something like:
Foo::bar: This is an error in /some/file at X