Dieser Beitrag ist auf mehrfachen Wunsch auf Englisch geschrieben und stellt einen bereits veröffentlichten Beitrag auf deutsch dar.
Each software developer knows the problem: writing software is just one part, testing and debugging is the other one. In php, there are some ways:
- you can use a debugger tool (like xdebug or dbg)
- or you can just print your variables to the output.
I love to develop my code with objects. I have to output these objects to check, if they have the expected values because there is no really good free debugger tool for current PHP versions. All of you know, that this can be done with this code:
var_dump($obj);
If you have complex objects, the output is annoying. The extension xdebug could help because it prints var_dump code in a readable way with colors.
But there is still one problem: the debug output will destroy your layout and you cannot check your system without destroying the design. There must be another solution: here it is:
If you are developing JavaScript code, you surely know the Firefox extension Firebug (documentation). This extensions is a fantastic tool to test your code, your output and your background traffic. But it also allows you to print debug messages with types:
This script….
<script type="text/javascript">
console.log("Log-Nachricht");
console.info("Info-Nachricht");
console.warh("Warnungs-Nachricht");
console.error("Fehlermeldung");
</script>
…creates:

You can see, that each message type has it’s own color.
You can print simple messages, but Firebug can do more: it can output objects: This script…
<script type="text/javascript">
var obj = new Object();
obj.var1 = "test";
obj.var2 = 3;
console.log(obj);
</script>
… creates…

with details:

Now, it would be fantastic, if such behaviour would be possible in PHP. And the good message is: it is possible. You only need the possibility to use JSON (which is part of PHP 5.2 and can be loaded in previous versions - PECL).
Now, I have written a little function, which will help you to debug your PHP code. You can download the debug function for firebug freely, of course.
The debug function helps you to print the variable name, simple variables, arrays and even objects. Here you can see an example:
class test {
public $var1;
public $var2;
public $var3;
}
$test = new test();
$test->var1="function";
$test->var2=4;
$test->var3="you";
debug("testClass",$test,DEBUG_TYPE_WARN);
You will get the output:

You can view each detail of the object like a JavaScript object:

There are a lot of situations to use this function: p.e. “set_exception_handler”:
function handleExceptionError($exception) {
debug("ExceptionHandler",$exception->getMessage(),DEBUG_TYPE_ERR);
debug("File/ Line",str_replace("\\","/",$exception->getFile()) . "::" . $exception->getLine(),DEBUG_TYPE_ERR);
}
set_exception_handler('handleExceptionError');
In this way, you can test and debug your code without destroying your layout.
Have fun!