Static class initializer in 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 中的静态类初始化器
 
				
         
 
            
        基础教程推荐
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- Web 服务器如何处理请求? 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- php中的foreach复选框POST 2021-01-01
- php中的PDF导出 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				