Debugging

By ukmodak | March 31st 2024 10:36:23 AM | viewed 502 times

Dumping variables to stdout

The var_dump function is one way to see what’s happening in your PHP program. It’ll dump a variable value to stdout. There are other functions you can use for debugging through outputs. Here are a few and how they’ll help you:

  1. var_dump ($var) dumps the variable type and value to stdout.
  2. print_r ($var) prints the variable value in human-readable form to stdout.
  3. get_defined_vars() gets all the defined variables including built-ins and custom variables (print_r to view them).
  4. debug_zval_dump ($var) dumps the variable with its reference counts. This is useful when there are multiple paths to update a single reference.
  5. debug_print_backtrace() prints a backtrace that shows the current function call-chain.
  6. debug_backtrace() gets the backtrace. You can print_r, log it to a file, or send it to a logging endpoint asynchronously.
$myVar = "hello world!";

var_dump($myVar);
print_r($myVar);

$allVars = get_defined_vars();
print_r($allVars);
debug_zval_dump($allVars);

function sayHello($hello) {
    echo $hello;
    debug_print_backtrace();
}

sayHello($myVar);

These functions are a quick way to debug your PHP code. You can see them in action in this Paiza. Each function has a purpose and can be useful for debugging.

Switching error reporting level

PHP has a few ways to configure error reporting. You can use the php.ini file, if you have access to it. Otherwise, you might use the htaccess configuration. If you can’t use configuration files, you have the option of changing the values via a script. This is possible, but think about how you would change modes after deploying your application.

A combination of settings will get you the right levels of error logging. You’ll want to consider the following settings:

  1. error_reporting sets the level of logging. E_NOTICE is useful during development since it will tell you about defects such as unassigned variables.
  2. display_errors tells PHP if and where to display error messages.
  3. display_startup_errors should only be used when debugging.
  4. log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users.

Stepping through code

We can use xdebug library and setup on IDE

bONEandALL
Visitor

Total : 27273

Today :9

Today Visit Country :

  • United States
  • Sweden
  • Singapore
  • Russia