2

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

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() 在调试程序时将它们打印出来。并在实际使用中将它们注释掉。

在实际运行模式和调试模式之间切换时,我没有逐行插入和删除注释符号'//',而是使用函数 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 解释器在调试模式下打印这些注释消息。我可以这样做吗?

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

我发现现在使用高级 IDE 和调试工具来开发我的程序对我来说非常复杂。我相信这些高级调试工具中的一些可以做与我想要的类似的事情,但我已经在 PHP-eclipse 和 xdebug 上尝试了一周,但它让我无处可去。非常感谢您。

4

2 回答 2

3

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

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到任何想要使用该功能的功能。

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

$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');
于 2012-05-01T12:27:01.817 回答
-1

没有芽,

不可能有这样的事情,并且您每次都必须定义一个条件。

这不能在 php 的代码中完成

于 2012-05-01T12:15:50.713 回答