PHP/Debugging

PHP Course > PHP Debugging

Introduction
Debugging PHP can become an arduous task at times. However, with the implementation of certain techniques, the time with which it takes to debug can be drastically reduced. This page will try to elaborate on the most useful of those techniques.

Compilation Debugging
More content is needed here.

Runtime Debugging
When dealing with runtime errors, the following steps should be followed:

Debugging Steps

 * 1) Determine the most probable point of error (this may take some guess and check)
 * 2) Print out the variable with the highest likelihood of error, or print all variables
 * 3) Stall the rest of the script execution
 * 4) Assess the variables contents
 * 5) Tweak the script and using guess and check, determine if the error has been removed

Essentially the goal is to see if your code is producing the expected result, and if not, tweaking the code until you have removed the error.

Example
Notice the second line contains a variable name that does not exist and is therefore null, so although we expect $$(5*4)+2=22$$ we will get $$2$$. By printing it out, we can realize that the error must occur on the second line, because that is only place in which $$2$$ is present. In doing so, we see that the variable $outpt, is just the incorrect spelling of $output, and we have found our error.

Function: print_r
This function allows you to print the contents of any variable, including a constructed object and an array. As discussed above, this can be used in part (2). PHP Manual: print_r

Returns

You can also utilize this to print out all of the variables that are defined (with global scope) at any point in the script. Using the statement: The $GLOBALS variables is discussed below.

Function: var_dump
This function is very similar to print_r, but it also gives more information on the type of variable as well as the defined value. PHP Manual: var_dump

Returns

Function: die and exit
The die and exit functions are equivalent. Both functions allows you to halt the execution of further code. This is very useful when debugging because it allows you to isolate the problem, and understand where the error is occurring.

Example

This will only return "Hello", because the script will have "died" after the call to the die function.

$GLOBALS
The $GLOBALS variable is an associative array containing all variables which are currently defined in the global scope. An understanding of variable scope may be required in understanding how $GLOBALS will not include variables that do not have global scope. However, for most intensive purposes, using $GLOBALS to find problems with code can be extremely useful.