PHP 单例类的最佳实践 [英] Best practice on PHP singleton classes
问题描述
可能的重复:
谁需要单身人士?
我总是根据最佳实践写作,但我也想了解为什么给定的事情是最佳实践.
I always write with respect to best practice, but I also want to understand why a given thing is a best practice.
我在一篇文章中读到(不幸的是我不记得了)单例类更喜欢被实例化,而不是使用静态函数创建并使用范围解析运算符 (::) 访问.因此,如果我有一个包含我所有验证工具的类,简而言之:
I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:
class validate {
private function __construct(){}
public static function email($input){
return true;
}
}
有人告诉我这被认为是不好的做法(或者至少被警告不要这样做),因为垃圾收集器和维护之类的事情.因此,对作为静态方法的单例类"的批评想要的是,我实例化一个类,我 100% 确定我只会实例化一次.对我来说,这似乎是在做双重工作",因为一切都准备好了.我错过了什么?
I've been told this is considered bad practice (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?
对此事有何看法?当然,这不是生死攸关的问题,但如果有选择的话,不妨以正确的方式做一件事:)
What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)
推荐答案
php 中的单例类示例:
在 PHP5 中创建单例设计模式:Ans 1:
在 PHP5 中创建单例设计模式:Ans 2 :
An example singleton classes in php:
Creating the Singleton design pattern in PHP5 : Ans 1 :
Creating the Singleton design pattern in PHP5 : Ans 2 :
Singleton 被认为是不好的做法".
主要是因为这个:如何在 PHP 中硬测试注册表模式或单例?
想阅读更多?:
单例决策图(来源):
这篇关于PHP 单例类的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!