php - 打开/关闭打印调试消息的功能

标签 php debugging function printing comments

我对编程很陌生,当我开发程​​序时,我使用一个简单的策略来调试它:例如,我编写程序以在运行重要语句时打印调试消息

function foo1($number)
{
  //foo_print("I am function foo1({$number}). <br/>");
  //foo_print("I am going to increase 'count' by {$number}. <br/>");

  $GLOBALS["count"] = $GLOBALS["count'] + $number;

  //foo_print("Now 'count' = {$GLOBALS["count"]}, I finished my task, BYE BYE. <br/>");

}

function isFoo($number)
{
  //foo_print("I am function isFoo({$number}). <br/>");
  //foo_print("I am checking if the number < 3 or not, if so, it is Foo, if not, it is not Foo. <br/>");
  if($number <= 3)
  {
    //foo_print("Found that number = {$number} <= 3, I return true, BYE BYE. <br/>");
    return true;
  }

  //foo_print("Found that number = {$number} > 3, I return false, BYE BYE. <br/>");
  return false;
}

我称它们为调试消息,但正如您所看到的,它们实际上是描述程序在每一行上执行的操作的完整注释。我只是编写函数 foo_print() 在调试程序时将它们打印出来。并在实际使用中将其注释掉。

在实际运行模式和 Debug模式之间切换时,我没有逐行插入和删除注释符号“//”,而是使用函数 foo_print 来完成这项工作:它可以设置为打开或关闭.

define(FOO_PRINT, 1)
function foo_print($message)
{
  if(FOO_PRINT) print $message;
  // if FOO_PRINT == 0 then do nothing.
}

但我认为这种方法效率不高,每次打印消息之前都必须检查FOO_PRINT。

我的问题是以下一个或两个

  • 当我不想使用 foo_print() 函数时,我可以做些什么来告诉 php 忽略它吗?

  • 也许,我不应该使用 foo_print 函数,而是应该使用“//”符号以普通注释样式编写消息,然后告诉 php 解释器在 Debug模式下打印这些注释消息。我可以这样做吗?

我想,这种方法除了调试方便之外,还有一个好处,就是以后我再看程序的时候,可以帮助我理解程序。 (对我来说又长又复杂,我相信我很快就会忘记它。)

我发现现在使用先进的IDE和调试工具来开发我的程序非常复杂。我相信这些高级调试工具中的一些可以完成与我想要的类似的事情,但我已经在 PHP-eclipse 和 xdebug 上尝试了一周,但一无所获。非常感谢。

最佳答案

您可以定义两个函数,其中一个输出调试数据,另一个不输出。然后使用变量名来包含要调用的函数的名称,并通过调用变量中的函数来进行调试。像这样:

function debug_print($data) {
    echo $data;
}
function debug_none($data) {
}

$debug = 'debug_print';
$debug('Testing one'); // This prints out 'Testing one'

$debug = 'debug_none';
$debug('Testing two'); // This doesn't print out anything

如果您这样做,请不要忘记将 global $debug 添加到任何想要使用该函数的函数中。

编辑:还有一种更面向对象的方法来实现相同的结果。您可以定义一个接口(interface)并为其编写几个实现,以便您选择在运行时使用哪一个。

$debugmode = true;

interface Debugger {
    public function out($data);
}

class EchoDebugger implements Debugger {
    public function out($data) {
        echo $data;
    }
}

class NullDebugger implements Debugger {
    public function out($data) {
        // Do nothing
    }
}

if($debugmode)
    $debugger = new EchoDebugger();
else
    $debugger = new NullDebugger();

$debugger->out('This will be output if $debugmode is true');

关于php - 打开/关闭打印调试消息的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10397454/

相关文章:

PHP:如何将 GZ 解压缩为字符串?

javascript - 删除所有保存内容的 Visual Composer Shortcodes

go - 如何在 VS Code 中调试 Ginkgo 测试?

javascript - 暂停功能,直到按下回车键javascript

c++ - 为什么函数参数求值不能排序?

php - 使用 .htaccess 和 php 重定向 url(如果它包含特定单词)

javascript - 从连接到 SQL 的 PHP 使用 AngularJS 读取 JSON 数据

spring - 当您 POST 到接受 HTTP GET 的 Controller 操作时,为什么 Spring MVC 不会抛出错误?

c++ - 调试有限状态机拼写检查程序代码

c - 函数调用的段错误