As a last resort, ( as others mentioned the preferred ways )
You can comment all the code out, and back track the code tell it stops, just be mindful of if{ } blocks and other control structures.
For example.. say you have this code.
<?php
function do_nothing(){
}
$somthing = 1;
if($something){
do_nothing();
}
$badCode = 'hello'
$array = array(1,2,3,4,5);
foreach($array as $item ){
echo 'item: '.$item;
}
outputs nothing, because it's broken.
You could
<?php
/*
function do_nothing(){
}
$somthing = 1;
if($something){
do_nothing();
}
$badCode = 'hello'
$array = array(1,2,3,4,5);
foreach($array as $item ){
echo 'item: '.$item;
}
*/
echo 'works';
outputs
'works'
And continue to
<?php
/*
function do_nothing(){
}
$somthing = 1;
if($something){
do_nothing();
}
$badCode = 'hello'
*/
$array = array(1,2,3,4,5); //need this for the loop
foreach($array as $item ){
//don't comment half this block
echo 'item: '.$item;
}
echo 'works';
Outputs
'item: 1'
'item: 2'
'item: 3'
'item: 4'
'item: 5'
'works'
And finally
<?php
/*
function do_nothing(){
}
$somthing = 1;
if($something){
do_nothing();
}
*/
$badCode = 'hello'
$array = array(1,2,3,4,5); //need this for the loop
foreach($array as $item ){
//don't comment half this block
echo 'item: '.$item;
}
echo 'works';
Broken, ( missing semicolon $badCode = 'hello'; )
It's a rudimentary way to debug, to be sure. but it will work 100% of the time if you respect the control blocks..
Also be sure to be familiar with the different print functions.
- echo — Output one or more strings
- print_r — Prints human-readable information about a variable
- var_export — Outputs or returns a parsable string representation of a variable
- var_dump — Dumps information about a variable
- debug_backtrace — Generates a backtrace
I'm sure there are more of these but those are the most common. Its also useful to use a <pre>
tag before printing objects and array to preserve the whitespace and make them easy to read.
I also like to use this little function ( which can tell you what line you printed from )
/**
* export a variable with line number from backtrace using offset
* @param mixed $var
* @param int $offset
*/
function print_debug($var=null, $offset=0){
$stacktrace = debug_backtrace(false);
$trace = $stacktrace[$offset];
extract($trace);
echo "<span style='color: #CCC;'> Output from FILE[ $file ] LINE[ $line ]</span>";
echo "<pre>";
var_export($var);
echo "</pre>";
}