Wednesday, October 12, 2011

Simple PHP Debugging with the Zend Framework

For simple debugging of code, it can be hard to beat php’s var_dump() function. It outputs all information about a given variable, and is very useful if you quickly need to see what a variable actually contains without using an in-depth debugging environment.
The only problem with var_dump() is that it often does not produce readable results without wrapping the output in <pre> tags so your browswer knows how to format it. Zend_Debug to the rescue!
It has to be noted that using Zend_Debug is at best an ad-hoc strategy and should not be used on production websites, as sensitive information may be presented to end users. With that being said, it is still an outstandingly simple and easy way to debug your code. For more secure and permanent debugging code, it is best to use the Zend_Log component.

The dump() Method

Zend_Debug only has one method, and it’s a static one: debug(). Its usage is quite simple:

Zend_Debug::dump($var);
Additionally, you can pass an optional second paramenter, $label, that will be prepended to the output. This is most useful if you will be dumping several vars and want to keep them separate, readable, and labeled.
A third, optional parameter, $echo, is also available. This boolean paremeter specifies whether or not to echo the output, and defaults to true. Regardless of whether this parameter is true or false, the output will also be returned by the function.
So if you wanted to get the output of Zend_Debug::dump() without showing it to the end user, you could do something like:

$dumpedVar = Zend_Debug::dump($var, '', false);
In conclusion, Zend_Debug is a simple way to debug your code, but don’t rely too heavily on it, and be wary of it in production environments. You don’t want to reveal potentially sensitive information about your site to users, not to mention the unprofessional impression given off by a site sending code to end users. Its main use is simple debugging in which you add and remove the debug code quickly, and before it does any damage.

No comments:

Post a Comment