Debugging PHP: Inspecting Variables

When debugging in PHP, we often want to know exactly what a variable is. We often know what it should be, but when things don’t work as expected, we need to know whether that’s really what it is. There are several ways to inspect variables in PHP. Among them are the following functions, listed with their downsides:

  • var_dump() – This one does great with all sorts of data types, but only outputs the result; not very useful in some situations, especially when you’re (yikes!) debugging live.
  • print_r() – This one is OK for some data types, but gives no output when passed false. On the upside, it can return the string instead of outputting it directly.
  • var_export() – This produces a parsable string, which can be useful at times, but can also be difficult to comprehend.

Of these, var_dump() is often the best for debugging, because it tells you what data type the variable is. The problem is that it only outputs the result directly, which can be annoying as I pointed out above. I prefer to use the error log when I’m debugging. So that’s why I use the function below. It works exactly like var_dump() the only difference is that it logs the result to the error log instead of outputting it.

 * Dump a variable to the error log.
 * You can pass as many variables as you want!
function var_log() {

	call_user_func_array( 'var_dump', func_get_args() );
	error_log( ob_get_clean() );

Think carefully before adding this to your development environment. You may find it hard to live without!

Leave a Reply

Your email address will not be published. Required fields are marked *