Debuging variables in Yii2

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

This tutorial is explained following "basic" application structure.

Create functions.php inside config folder and place this code:

<?php

/**
 * Debug function
 * d($var);
 */
function d($var,$caller=null)
{
    if(!isset($caller)){
        $caller = array_shift(debug_backtrace(1));
    }
    echo '<code>File: '.$caller['file'].' / Line: '.$caller['line'].'</code>';
    echo '<pre>';
    yii\helpers\VarDumper::dump($var, 10, true);
    echo '</pre>';
}

/**
 * Debug function with die() after
 * dd($var);
 */
function dd($var)
{
    $caller = array_shift(debug_backtrace(1));
    d($var,$caller);
    die();
}

Open config/web.php file and include functions.php :

<?php

/* Include debug functions */
require_once(__DIR__.'/functions.php');

$params = require(__DIR__ . '/params.php');
$database = require(__DIR__ . '/database.php');
...

Now you can use debug functions like this:

d($test);
dd($var);

These debug functions will display what variables contain in readable manner, as well as display where the debug call has been called (in which file and on what line of file).

4 1
8 followers
Viewed: 41 989 times
Version: Unknown (update)
Category: Tips
Written by: johonunu
Last updated by: johonunu
Created on: Feb 19, 2015
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles