Easy ways to Debug PHP code

Printing debug information out into the page is one of the most common tasks during PHP application development. It is a very convenient feature of any dynamically typed scripting language – at any place in your code you can add a single line and print the debug information on the next run, without long application compilation times. Certainly, there is more than one way of displaying debug information, even more certainly, some are more useful than others. 

Output functions and variations

There are two basic groups of information outputting constructs in PHP

  • Output a string value
  • Format any type of value and return / output a string value

A string value can be outputted in several ways:

<?php
echo "string to output";
print("string to output");

Those constructs output string as is without any modifications. If anyone to use this method, you would need to construct your debug message in a way that shows the full picture of the process you wish to investigate.

In more complex programs you would rarely be debugging string variables, but mostly arrays / objects / more complex constructs. There are several variable handling functions to work with such types of constructs.

One of the easiest to use and most popular is print_r function. The usage is fairly simple:

<?php
# create an array to output
$debug = [1, 4, 9, 16, 25];
# print the array
print_r($debug);
# output
# Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 ) 

Note that the output is different between running the script from console and opening in web browser. Console displays \n (line break) and \t (tabulation) symbols appropriately. Web browser looks for HTML symbols, so special characters are usually ignored. To display those characters similarly to console, use HTML<pre> tag.

<?php
# create an array to output
$debug = [1, 4, 9, 16, 25];
# output opening <pre> tag
echo '<pre>';
# output the array
print_r($debug);
# output closing tag
echo '</pre>';

The print_r function has a second parameter, which when set to true will return the information rather than print it. This can help with saving complex arrays / objects for debug purposes into a database or log file. Also printing the debug information becomes easier.

<?php
# create an array to output
$debug = [1, 4, 9, 16, 25];
# output opening <pre> tag
echo '<pre>' . print_r($debug, true) . '</pre>;

Another method which is capable of printing all kinds of variable types is var_dump, which accepts one or more variables and prints them with type hints. In this example it will output both types and lengths of the variable values.

<?php
# create an array to output
$debug = [1, 4, 9, 16, 25];
# dump the array
var_dump($debug);
# output
# array(5) { [0]=> int(1) [1]=> int(4) [2]=> int(9) [3]=> int(16) [4]=> int(25) } 

If there is a need to get this output as a string, you can always use output-control functions for this.

<?php
# create an array to output
$debug = [1, 4, 9, 16, 25];
# enable output buffer
ob_start();
# dump the array
var_dump($debug);
# get data from the buffer as a string and clean the buffer
$output = ob_get_clean();
# output your string
echo '<pre>' . $output . '</pre>';

When dumping objects with var_dump can use a magic method called __debugInfo of an object. The method have to return an array of values, which will be outputted as set of properties for an object. This is useful when you need to add more information to the debugging session, or, on the contrary, hide private information from the debug output.

Usually var_dump works with objects in the following way

<?php

class MyClass {
    /** @var string|null */
    private $attributeOne;
    /** @var string */
    public $attributeTwo = '';

    /**
     * @return null|string
     */
    public function getAttributeOne()
    {
        return $this->attributeOne;
    }

    /**
     * @param null|string $attributeOne
     */
    public function setAttributeOne(string $attributeOne = null)
    {
        $this->attributeOne = $attributeOne;
    }

    /**
     * @return string
     */
    public function getAttributeTwo()
    {
        return $this->attributeTwo;
    }

    /**
     * @param string $attributeTwo
     */
    public function setAttributeTwo(string $attributeTwo)
    {
        $this->attributeTwo = $attributeTwo;
    }
}

$object = new MyClass();
$object->setAttributeOne('one');
$object->setAttributeTwo('two');
var_dump($object);

In this example var_dump will output the following information

object(MyClass)#1 (2) {
  ["attributeOne":"MyClass":private]=>
  string(3) "one"
  ["attributeTwo"]=>
  string(3) "two"
}

The next example shows how you can hide attributeOne property from the output and add attributeWhichDoesNotExist to the output using __debugInfo method.

<?php

class MyClass {
    /** @var string|null */
    private $attributeOne;
    /** @var string */
    public $attributeTwo = '';

    /**
     * @return null|string
     */
    public function getAttributeOne()
    {
        return $this->attributeOne;
    }

    /**
     * @param null|string $attributeOne
     */
    public function setAttributeOne(string $attributeOne = null)
    {
        $this->attributeOne = $attributeOne;
    }

    /**
     * @return string
     */
    public function getAttributeTwo()
    {
        return $this->attributeTwo;
    }

    /**
     * @param string $attributeTwo
     */
    public function setAttributeTwo(string $attributeTwo)
    {
        $this->attributeTwo = $attributeTwo;
    }

    /**
     * @return array
     */
    public function __debugInfo()
    {
        return [
            'attributeTwo' => $this->getAttributeTwo(),
            'attributeWhichDoesNotExist' => 'existsNowInDebug'
        ];
    }
}

$object = new MyClass();
$object->setAttributeOne('one');
$object->setAttributeTwo('two');
var_dump($object);

This will output

object(MyClass)#1 (2) {
  ["attributeTwo"]=>
  string(3) "two"
  ["attributeWhichDoesNotExist"]=>
  string(16) "existsNowInDebug"
}

For the most cases var_dump is the most suitable function, as it provides most information and is fairly simple to use. However, if you wish to get debug information with colors, there are some easy ways to accomplish this.

Method var_export is an alternative to print_r, but instead of printing out some version of the variable, it prints the variable definition (as PHP code).  Here is an example of how that would be look with a simple array.

<?php
# create an array to output
$debug = [1, 4, 9, 16, 25];
# enable output buffer
var_export($debug);
# output
# array ( 0 => 1, 1 => 4, 2 => 9, 3 => 16, 4 => 25, )

For objects this definition looks a little different, but nonetheless usable for debugging purposes.

MyClass::__set_state(array(
   'attributeOne' => 'one',
   'attributeTwo' => 'two',
))

The cool thing about this function is that it goes well with highlight_string function, which takes as an argument valid PHP code and outputs it’s colored version! This works only in browsers though, because the coloring is done using HTML tags.

Outputting colored debug into the browser would look like thi

# define the object
$object = new MyClass();
$object->setAttributeOne('one');
$object->setAttributeTwo('two');
# get object definition
$debug = var_export($object, true);
# make it a valid php code (add php tag)
$debugAsValidPHPCode = '<?php ' . $debug;
# get colored debug
$debugHighlighted = highlight_string($debugAsValidPHPCode, true);
# remove PHP tag
$debugWithoutPHPTag = str_replace('<?php ', '', $debugHighlighted);
# output debug string
echo $debugWithoutPHPTag;

Nothing too complex, but it get’s you the colored information about the object

MyClass::__set_state(array(
   
‘attributeOne’ => ‘one’,
   
‘attributeTwo’ => ‘two’,
))

Hope this small overview of PHP capabilities in outputting things helps you with your debugging!

Leave a Reply

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