dpyln64620 2010-07-22 19:49
浏览 119
已采纳

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?

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.

  • 写回答

7条回答 默认 最新

  • douhuai2861 2010-07-22 19:56
    关注

    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
      }
    }
    

    And then, in usage

    // As opposed to this
    Singleton::someMethod1();
    
    // You'd do this
    Singleton::getInstance()->someMethod1();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.