我有一个带有一些静态函数的辅助类。类中的所有函数都需要一个“繁重”的初始化函数才能运行一次(就好像它是一个构造函数一样)。
是否有实现此目的的良好做法?
我唯一想到的是调用 init
函数,如果它已经运行过一次(使用静态 $initialized
var),则中断其流程。问题是我需要在每个类的函数上调用它。
最佳答案
听起来你最好使用单例而不是一堆静态方法
class Singleton
{
/**
*
* @var Singleton
*/
private static $instance;
private function __construct()
{
// Your "heavy" initialization stuff here
}
public static function getInstance()
{
if ( is_null( self::$instance ) )
{
self::$instance = new self();
}
return self::$instance;
}
public function someMethod1()
{
// whatever
}
public function someMethod2()
{
// whatever
}
}
然后,在使用中
// As opposed to this
Singleton::someMethod1();
// You'd do this
Singleton::getInstance()->someMethod1();
https://stackoverflow.com/questions/3312806/