我可以为Logger使用静态类吗? [英] Can I use static class for my Logger?
本文介绍了我可以为Logger使用静态类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我被告知静态类/方法是邪恶的.
Recently I have been told that static class/methods are evil.
以我的类Logger为例:
Take for example my class Logger:
class Logger{
private static $logs = array();
public static function add($msg){
self::$logs[]=$msg;
}
public static function echo(){
print_r(self::$logs);
}
}
我可以随时在应用中使用这样的东西:
I can use whenever i want in my appliaction like this:
Logger::add('My log 1');
但是请阅读此开发人员:
But reading this developers:
该Logger类似乎不太好.
That Logger class doesn't seem so good.
所以:我可以静态使用它还是应该不惜一切代价避免使用它?
So: Can I use it statically or I should avoid it at any cost?
推荐答案
记录类是例外.
由于它们很少包含太多逻辑,因此您不必担心相同的测试问题.
Since they rarely contain much logic, you don't have the same testing concerns.
记录是使用静态类的一个好地方的完美示例.
Logging is a perfect example of a GOOD place to use static classes.
考虑其他选择:
- 日志对象的全局实例?
- 单例记录对象?
- 将日志记录对象传递给每个方法/类(通过构造函数)?
以上内容比使用static
进行记录要糟糕得多.
The above are much worse than using static
for logging.
这篇关于我可以为Logger使用静态类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文