Using Conditional Statements with the Xdebug Extension - Debugging conditionals with the xdebug_start_code_coverage() and xdebug_get_code_coverage() functions (
Page 4 of 4 )
To complete the practical example developed in the prior section, it’s necessary to show the output produced by the script when the “rand()” PHP function returns a value greater than five to client code.
In that particular case, the “xdebug_start_code_coverage()” and “xdebug_get_code_coverage()” functions will display on screen the sequence of lines being executed within the second block of code, instead of the instructions wrapped in the first one.
But undoubtedly, this process will be better understood if you examine the following code sample, which represents this situation in a clear manner:
xdebug_start_code_coverage();
$user=new User('John','Doe','john@domain.com');
if(rand(1,10)<5){
echo 'First Name :'.$user->getFirstName().'<br />';
echo 'Last Name :'.$user->getLastName().'<br />';
}
else{
echo 'Email :'.$user->getEmail().'<br />';
}
var_dump(xdebug_get_code_coverage());
/* displays the following when the 'rand()' function returns a value > 5
Email :john@domain.com
array
'/path/to/example/program_flow_debug.php' =>
array
8 => int 1
11 => int 1
14 => int 1
17 => int 1
18 => int 1
19 => int 1
20 => int 1
31 => int 1
36 => int 1
37 => int 1
42 => int 1
44 => int 1
*/
Definitely, the example shown above should be extremely simple for you to grasp. All it does is show the output generated by the xdebug_start_code_coverage()” and “xdebug_get_code_coverage()” functions when the second block of code is executed by the previous script. See how easy it is to use these functions along with conditional statements to keep track of the flow followed by a PHP application? I bet you do!
The best way to grasp how those functions do their work, however, is with lots of practice. Thus, feel free to tweak all of the code samples included in this tutorial, so you can acquire a more solid background in using these handy functions provided by the Xdebug extension.
Final thoughts
In this fifth chapter of the series, I walked you through using the "xdebug_start_code_coverage()” and “xdebug_get_code_coverage()” functions, which can be really useful for debugging execution flow of a PHP application.
However, this educational journey of exploring the Xdebug library hasn’t finished yet, since it includes a few other functions that deserve a close analysis. Therefore, in the next article I’ll be taking a look at the “xdebug_index_time()” function, which can be used for benchmarking PHP scripts very easily.
This is my little piece of advice: don’t miss the upcoming tutorial!