PHP 中的静态类初始化器

2021-12-30 00:00:00 class constructor static initializer php

我有一个带有一些静态函数的辅助类.类中的所有函数都需要一个重"的初始化函数来运行一次(就像它是一个构造函数).

I have an helper class with some static functions. All the functions in the class require a ‘heavy’ initialization function to run once (as if it were a constructor).

是否有实现这一目标的良好做法?

Is there a good practice for achieving this?

我唯一想到的是调用一个 init 函数,如果它已经运行过一次(使用静态 $initialized 变量),就中断它的流程.问题是我需要在类的每一个函数上调用它.

The only thing I thought of was calling an init function, and breaking its flow if it has already run once (using a static $initialized var). The problem is that I need to call it on every one of the class’s functions.

推荐答案

听起来像使用单例而不是一堆静态方法更好

Sounds like you'd be better served by a singleton rather than a bunch of static methods

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();

相关文章