沃梦达 / 编程问答 / php问题 / 正文

PHP 中的静态类初始化器

Static class initializer in PHP(PHP 中的静态类初始化器)

本文介绍了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();

这篇关于PHP 中的静态类初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP 中的静态类初始化器

基础教程推荐