dongtao9158 2015-03-24 14:18
浏览 19

在PHP中添加可选的debug / verbose输出,占用空间最小

Currently I develop a library in PHP. This library uses it's own namespace. To store global (in the scope of the library's namespace) settings I use a static class, similar to this:

class Settings {
    public static $verbose = true;
}

To make verbose output easy and adaptable I use a static method like this one:

class Log {
    public static function v($msg) {
        if ( ! Settings::$verbose) { return; }
        echo $msg . "<br>
";
    }
}

This way I can easily add verbose output to my code:

Log::v('Answering questions...');
echo '42';

However, this approach creates lot's of unnecessary method calls which return immediately when verbose output is deactivated.

Now I thought about changing my approach in the following way:

class Log {

    public static $v = false;

    public static function init() {
        self::$v = Settings::$verbose;
    }

    public static function v($msg) {
        echo $msg . "<br>
";
    }

}

I copy the value of Settings::$verbose to Log::$v just because that's shorter. Now - after calling Log::init() once - my verbose output line looks like this:

Log::$v && Log::v('All questions answered.');

But this line is not as neat/short as simply typing Log::v(''). I don't like the idea of having to type Log::$v && Log::v('') whenever I want to add information about what's going on.

My question is: Is there another way to add verbose output with a minimal footprint? Are there any inbuilt functions in PHP which I'm not aware of?

To avoid conflicts with other components I want to keep things within the library's namespace, so I don't want to use a global constant like define('V', true).

Update: I just recognized that constants can be namespaced, thus I could change my second approach to:

define(__NAMESPACE__ . '\V', true);
V && Log::v('...');

But my questions remains...

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 docker里部署springboot项目,访问不到扬声器
    • ¥15 netty整合springboot之后自动重连失效
    • ¥15 悬赏!微信开发者工具报错,求帮改
    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法