如何在 Yii 中转储变量以进行调试?

How do I dump variables in Yii for debugging?

如何在 Yii 中转储和打印变量以进行调试?我想使用 var_dump()print_r()。我尝试使用 Yii::trace() 但它因 runtime/logs/app.log 中的此错误而崩溃。它甚至没有告诉我代码中的那一行它失败了。

2015-03-18 20:54:11 [::1][-][-][warning][yii\log\Dispatcher::dispatch] Unable to send log via yii\debug\LogTarget: Exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'

in /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2-debug/LogTarget.php:58

Stack trace:
#0 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2-debug/LogTarget.php(58): serialize(Array)
#1 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2-debug/LogTarget.php(112): yii\debug\LogTarget->export(Array)
#2 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2/log/Dispatcher.php(183): yii\debug\LogTarget->collect(Array, true)
#3 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2/log/Logger.php(170): yii\log\Dispatcher->dispatch(Array, true)
#4 [internal function]: yii\log\Logger->flush(true)
#5 {main}

参考 http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html

我用过这个,但我相信还有更好的方法。

Yii::warning('**********************', var_export($category,true));
config/web.php
    'log' => [
        ...
        'flushInterval' => 1, // for debug
        'targets' => [
            [
                ...
                'exportInterval' => 1, // for debug - slow
            ],
        ],
    ],

因为您问的是 var_dumpprint_r 之类的问题,我可以为此建议内置帮助程序。它被称为 yii\helpers\VarDumper. Yii::trace() 用于记录跟踪消息。

VarDumper is intended to replace the buggy PHP function var_dump and print_r.

It can correctly identify the recursively referenced objects in a complex object structure. It also has a recursive depth control to avoid indefinite recursive display of some peculiar variables.

VarDumper can be used as follows,

VarDumper::dump($var);

我个人不使用它,只是尝试了几次进行测试。

我认为为此目的使用 Xdebug 更好。

另见 PsySH

我写过一篇关于 Yii 2 调试变量问题的文章:

Since for the sake of Simplicity and Quick Development, I’ve created a helper for those who use Yii. You can just call dd($var1, $var2, ….); for dump & die or d($var1, $var2, ….); for dump data.

详细信息和安装说明在:https://dangnhsite.wordpress.com/2016/04/06/variable-debug-in-yii-2/

使用这个:

<?php echo '<pre>'; print_r($model); exit; ?>

使用它来查看您的变量或对象数组。

use yii\helpers\VarDumper;

VarDumper::dump($variableArray , $dept = 10, $highlight = true);

详细信息你可以阅读文档 http://www.yiiframework.com/doc-2.0/yii-helpers-basevardumper.html#dump()-detail

你可以自己做: 在您的主索引页面(back/index.phpfront/index.php)中将此代码添加到顶部 ob_start();。然后定义2个函数以便更好的调试

function dd($v){
    ob_clean(); 
    var_dump($v);
    exit;
}
function dj($v){
    ob_clean(); 
    echo CJSON::encode($v);
    exit;
}

并在主索引页的末尾添加 ob_end_flush();。现在您可以调用 dd($model)dj($model)。你的自卸车在那里工作。恭喜!